Socket
Socket
Sign inDemoInstall

@opentelemetry/sdk-metrics-base

Package Overview
Dependencies
Maintainers
2
Versions
22
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@opentelemetry/sdk-metrics-base - npm Package Compare versions

Comparing version 0.27.0 to 0.28.0

build/esm/aggregator/Drop.d.ts

25

build/esm/index.d.ts

@@ -1,14 +0,17 @@

export * from './BoundInstrument';
export * from './CounterMetric';
export * from './HistogramMetric';
export { Histogram } from './aggregator/types';
export * from './export/AggregationTemporality';
export * from './export/MetricData';
export { MeterProvider, MeterProviderOptions } from './MeterProvider';
export * from './export/MetricExporter';
export * from './export/MetricProducer';
export * from './export/MetricReader';
export * from './export/PeriodicExportingMetricReader';
export { InstrumentDescriptor, InstrumentType } from './InstrumentDescriptor';
export * from './Meter';
export * from './MeterProvider';
export * from './Metric';
export * from './ObservableGaugeMetric';
export * from './export/aggregators';
export * from './export/ConsoleMetricExporter';
export * from './export/Processor';
export * from './export/types';
export * from './UpDownCounterMetric';
export { MeterConfig } from './types';
export * from './ObservableResult';
export { TimeoutError } from './utils';
export * from './view/Aggregation';
export { FilteringAttributesProcessor } from './view/AttributesProcessor';
export * from './aggregator/types';
//# sourceMappingURL=index.d.ts.map

@@ -16,14 +16,17 @@ /*

*/
export * from './BoundInstrument';
export * from './CounterMetric';
export * from './HistogramMetric';
export * from './export/AggregationTemporality';
export * from './export/MetricData';
export { MeterProvider } from './MeterProvider';
export * from './export/MetricExporter';
export * from './export/MetricProducer';
export * from './export/MetricReader';
export * from './export/PeriodicExportingMetricReader';
export { InstrumentType } from './InstrumentDescriptor';
export * from './Meter';
export * from './MeterProvider';
export * from './Metric';
export * from './ObservableGaugeMetric';
export * from './export/aggregators';
export * from './export/ConsoleMetricExporter';
export * from './export/Processor';
export * from './export/types';
export * from './UpDownCounterMetric';
export * from './ObservableResult';
export { TimeoutError } from './utils';
export * from './view/Aggregation';
export { FilteringAttributesProcessor } from './view/AttributesProcessor';
export * from './aggregator/types';
//# sourceMappingURL=index.js.map

@@ -1,92 +0,34 @@

import * as api from '@opentelemetry/api-metrics';
import { InstrumentationLibrary } from '@opentelemetry/core';
import { Processor } from './export/Processor';
import { MeterConfig } from './types';
import * as metrics from '@opentelemetry/api-metrics';
import { MeterSharedState } from './state/MeterSharedState';
/**
* Meter is an implementation of the {@link Meter} interface.
* This class implements the {@link metrics.Meter} interface.
*/
export declare class Meter implements api.Meter {
private readonly _metrics;
private readonly _processor;
private readonly _resource;
private readonly _instrumentationLibrary;
private readonly _controller;
private _isShutdown;
private _shuttingDownPromise;
export declare class Meter implements metrics.Meter {
private _meterSharedState;
constructor(_meterSharedState: MeterSharedState);
/**
* Constructs a new Meter instance.
* Create a {@link metrics.Histogram} instrument.
*/
constructor(instrumentationLibrary: InstrumentationLibrary, config?: MeterConfig);
createHistogram(name: string, options?: metrics.HistogramOptions): metrics.Histogram;
/**
* Creates and returns a new {@link Histogram}.
* @param name the name of the metric.
* @param [options] the metric options.
* Create a {@link metrics.Counter} instrument.
*/
createHistogram(name: string, options?: api.MetricOptions): api.Histogram;
createCounter(name: string, options?: metrics.CounterOptions): metrics.Counter;
/**
* Creates a new counter metric. Generally, this kind of metric when the
* value is a quantity, the sum is of primary interest, and the event count
* and value distribution are not of primary interest.
* @param name the name of the metric.
* @param [options] the metric options.
* Create a {@link metrics.UpDownCounter} instrument.
*/
createCounter(name: string, options?: api.MetricOptions): api.Counter;
createUpDownCounter(name: string, options?: metrics.UpDownCounterOptions): metrics.UpDownCounter;
/**
* Creates a new `UpDownCounter` metric. UpDownCounter is a synchronous
* instrument and very similar to Counter except that Add(increment)
* supports negative increments. It is generally useful for capturing changes
* in an amount of resources used, or any quantity that rises and falls
* during a request.
*
* @param name the name of the metric.
* @param [options] the metric options.
* Create a ObservableGauge instrument.
*/
createUpDownCounter(name: string, options?: api.MetricOptions): api.UpDownCounter;
createObservableGauge(name: string, callback: metrics.ObservableCallback, options?: metrics.ObservableGaugeOptions): void;
/**
* Creates a new `ObservableGauge` metric.
* @param name the name of the metric.
* @param [options] the metric options.
* @param [callback] the observable gauge callback
* Create a ObservableCounter instrument.
*/
createObservableGauge(name: string, options?: api.MetricOptions, callback?: (observableResult: api.ObservableResult) => unknown): api.ObservableGauge;
createObservableCounter(name: string, options?: api.MetricOptions, callback?: (observableResult: api.ObservableResult) => unknown): api.ObservableCounter;
createObservableCounter(name: string, callback: metrics.ObservableCallback, options?: metrics.ObservableCounterOptions): void;
/**
* Creates a new `ObservableUpDownCounter` metric.
* @param name the name of the metric.
* @param [options] the metric options.
* @param [callback] the observable gauge callback
* Create a ObservableUpDownCounter instrument.
*/
createObservableUpDownCounter(name: string, options?: api.MetricOptions, callback?: (observableResult: api.ObservableResult) => unknown): api.ObservableUpDownCounter;
/**
* Collects all the metrics created with this `Meter` for export.
*
* Utilizes the processor to create checkpoints of the current values in
* each aggregator belonging to the metrics that were created with this
* meter instance.
*/
collect(): Promise<void>;
getProcessor(): Processor;
shutdown(): Promise<void>;
/**
* Registers metric to register.
* @param name The name of the metric.
* @param metric The metric to register.
*/
private _registerMetric;
/**
* Ensure a metric name conforms to the following rules:
*
* 1. They are non-empty strings
*
* 2. The first character must be non-numeric, non-space, non-punctuation
*
* 3. Subsequent characters must be belong to the alphanumeric characters,
* '_', '.', and '-'.
*
* Names are case insensitive
*
* @param name Name of metric to be created
*/
private _isValidName;
createObservableUpDownCounter(name: string, callback: metrics.ObservableCallback, options?: metrics.ObservableUpDownCounterOptions): void;
}
//# sourceMappingURL=Meter.d.ts.map

@@ -16,265 +16,56 @@ /*

*/
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
import { diag } from '@opentelemetry/api';
import * as api from '@opentelemetry/api-metrics';
import { Resource } from '@opentelemetry/resources';
import { CounterMetric } from './CounterMetric';
import { PushController } from './export/Controller';
import { NoopExporter } from './export/NoopExporter';
import { UngroupedProcessor } from './export/Processor';
import { ObservableCounterMetric } from './ObservableCounterMetric';
import { DEFAULT_CONFIG, DEFAULT_METRIC_OPTIONS } from './types';
import { UpDownCounterMetric } from './UpDownCounterMetric';
import { ObservableUpDownCounterMetric } from './ObservableUpDownCounterMetric';
import { ObservableGaugeMetric } from './ObservableGaugeMetric';
import { HistogramMetric } from './HistogramMetric';
// eslint-disable-next-line @typescript-eslint/no-var-requires
var merge = require('lodash.merge');
// @TODO - replace once the core is released
// import { merge } from '@opentelemetry/core';
import { createInstrumentDescriptor, InstrumentType } from './InstrumentDescriptor';
import { CounterInstrument, HistogramInstrument, UpDownCounterInstrument } from './Instruments';
/**
* Meter is an implementation of the {@link Meter} interface.
* This class implements the {@link metrics.Meter} interface.
*/
var Meter = /** @class */ (function () {
/**
* Constructs a new Meter instance.
*/
function Meter(instrumentationLibrary, config) {
if (config === void 0) { config = {}; }
var _a;
this._metrics = new Map();
this._isShutdown = false;
this._shuttingDownPromise = Promise.resolve();
var mergedConfig = merge({}, DEFAULT_CONFIG, config);
this._processor = (_a = mergedConfig.processor) !== null && _a !== void 0 ? _a : new UngroupedProcessor();
this._resource =
mergedConfig.resource || Resource.empty();
this._instrumentationLibrary = instrumentationLibrary;
// start the push controller
var exporter = mergedConfig.exporter || new NoopExporter();
var interval = mergedConfig.interval;
this._controller = new PushController(this, exporter, interval);
function Meter(_meterSharedState) {
this._meterSharedState = _meterSharedState;
}
/**
* Creates and returns a new {@link Histogram}.
* @param name the name of the metric.
* @param [options] the metric options.
* Create a {@link metrics.Histogram} instrument.
*/
Meter.prototype.createHistogram = function (name, options) {
if (!this._isValidName(name)) {
diag.warn("Invalid metric name " + name + ". Defaulting to noop metric implementation.");
return api.NOOP_HISTOGRAM_METRIC;
}
var opt = __assign(__assign({}, DEFAULT_METRIC_OPTIONS), options);
var histogram = new HistogramMetric(name, opt, this._processor, this._resource, this._instrumentationLibrary);
this._registerMetric(name, histogram);
return histogram;
var descriptor = createInstrumentDescriptor(name, InstrumentType.HISTOGRAM, options);
var storage = this._meterSharedState.registerMetricStorage(descriptor);
return new HistogramInstrument(storage, descriptor);
};
/**
* Creates a new counter metric. Generally, this kind of metric when the
* value is a quantity, the sum is of primary interest, and the event count
* and value distribution are not of primary interest.
* @param name the name of the metric.
* @param [options] the metric options.
* Create a {@link metrics.Counter} instrument.
*/
Meter.prototype.createCounter = function (name, options) {
if (!this._isValidName(name)) {
diag.warn("Invalid metric name " + name + ". Defaulting to noop metric implementation.");
return api.NOOP_COUNTER_METRIC;
}
var opt = __assign(__assign({}, DEFAULT_METRIC_OPTIONS), options);
var counter = new CounterMetric(name, opt, this._processor, this._resource, this._instrumentationLibrary);
this._registerMetric(name, counter);
return counter;
var descriptor = createInstrumentDescriptor(name, InstrumentType.COUNTER, options);
var storage = this._meterSharedState.registerMetricStorage(descriptor);
return new CounterInstrument(storage, descriptor);
};
/**
* Creates a new `UpDownCounter` metric. UpDownCounter is a synchronous
* instrument and very similar to Counter except that Add(increment)
* supports negative increments. It is generally useful for capturing changes
* in an amount of resources used, or any quantity that rises and falls
* during a request.
*
* @param name the name of the metric.
* @param [options] the metric options.
* Create a {@link metrics.UpDownCounter} instrument.
*/
Meter.prototype.createUpDownCounter = function (name, options) {
if (!this._isValidName(name)) {
diag.warn("Invalid metric name " + name + ". Defaulting to noop metric implementation.");
return api.NOOP_COUNTER_METRIC;
}
var opt = __assign(__assign({}, DEFAULT_METRIC_OPTIONS), options);
var upDownCounter = new UpDownCounterMetric(name, opt, this._processor, this._resource, this._instrumentationLibrary);
this._registerMetric(name, upDownCounter);
return upDownCounter;
var descriptor = createInstrumentDescriptor(name, InstrumentType.UP_DOWN_COUNTER, options);
var storage = this._meterSharedState.registerMetricStorage(descriptor);
return new UpDownCounterInstrument(storage, descriptor);
};
/**
* Creates a new `ObservableGauge` metric.
* @param name the name of the metric.
* @param [options] the metric options.
* @param [callback] the observable gauge callback
* Create a ObservableGauge instrument.
*/
Meter.prototype.createObservableGauge = function (name, options, callback) {
if (options === void 0) { options = {}; }
if (!this._isValidName(name)) {
diag.warn("Invalid metric name " + name + ". Defaulting to noop metric implementation.");
return api.NOOP_OBSERVABLE_GAUGE_METRIC;
}
var opt = __assign(__assign({}, DEFAULT_METRIC_OPTIONS), options);
var observableGauge = new ObservableGaugeMetric(name, opt, this._processor, this._resource, this._instrumentationLibrary, callback);
this._registerMetric(name, observableGauge);
return observableGauge;
Meter.prototype.createObservableGauge = function (name, callback, options) {
var descriptor = createInstrumentDescriptor(name, InstrumentType.OBSERVABLE_GAUGE, options);
this._meterSharedState.registerAsyncMetricStorage(descriptor, callback);
};
Meter.prototype.createObservableCounter = function (name, options, callback) {
if (options === void 0) { options = {}; }
if (!this._isValidName(name)) {
diag.warn("Invalid metric name " + name + ". Defaulting to noop metric implementation.");
return api.NOOP_OBSERVABLE_COUNTER_METRIC;
}
var opt = __assign(__assign({}, DEFAULT_METRIC_OPTIONS), options);
var observableCounter = new ObservableCounterMetric(name, opt, this._processor, this._resource, this._instrumentationLibrary, callback);
this._registerMetric(name, observableCounter);
return observableCounter;
};
/**
* Creates a new `ObservableUpDownCounter` metric.
* @param name the name of the metric.
* @param [options] the metric options.
* @param [callback] the observable gauge callback
* Create a ObservableCounter instrument.
*/
Meter.prototype.createObservableUpDownCounter = function (name, options, callback) {
if (options === void 0) { options = {}; }
if (!this._isValidName(name)) {
diag.warn("Invalid metric name " + name + ". Defaulting to noop metric implementation.");
return api.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC;
}
var opt = __assign(__assign({}, DEFAULT_METRIC_OPTIONS), options);
var observableUpDownCounter = new ObservableUpDownCounterMetric(name, opt, this._processor, this._resource, this._instrumentationLibrary, callback);
this._registerMetric(name, observableUpDownCounter);
return observableUpDownCounter;
Meter.prototype.createObservableCounter = function (name, callback, options) {
var descriptor = createInstrumentDescriptor(name, InstrumentType.OBSERVABLE_COUNTER, options);
this._meterSharedState.registerAsyncMetricStorage(descriptor, callback);
};
/**
* Collects all the metrics created with this `Meter` for export.
*
* Utilizes the processor to create checkpoints of the current values in
* each aggregator belonging to the metrics that were created with this
* meter instance.
* Create a ObservableUpDownCounter instrument.
*/
Meter.prototype.collect = function () {
return __awaiter(this, void 0, void 0, function () {
var metricsRecords;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
metricsRecords = Array.from(this._metrics.values()).map(function (metric) {
return metric.getMetricRecord();
});
return [4 /*yield*/, Promise.all(metricsRecords).then(function (records) {
records.forEach(function (metrics) {
metrics.forEach(function (metric) { return _this._processor.process(metric); });
});
})];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
Meter.prototype.createObservableUpDownCounter = function (name, callback, options) {
var descriptor = createInstrumentDescriptor(name, InstrumentType.OBSERVABLE_UP_DOWN_COUNTER, options);
this._meterSharedState.registerAsyncMetricStorage(descriptor, callback);
};
Meter.prototype.getProcessor = function () {
return this._processor;
};
Meter.prototype.shutdown = function () {
var _this = this;
if (this._isShutdown) {
return this._shuttingDownPromise;
}
this._isShutdown = true;
this._shuttingDownPromise = new Promise(function (resolve, reject) {
Promise.resolve()
.then(function () {
return _this._controller.shutdown();
})
.then(resolve)
.catch(function (e) {
reject(e);
});
});
return this._shuttingDownPromise;
};
/**
* Registers metric to register.
* @param name The name of the metric.
* @param metric The metric to register.
*/
Meter.prototype._registerMetric = function (name, metric) {
if (this._metrics.has(name)) {
diag.error("A metric with the name " + name + " has already been registered.");
return;
}
this._metrics.set(name, metric);
};
/**
* Ensure a metric name conforms to the following rules:
*
* 1. They are non-empty strings
*
* 2. The first character must be non-numeric, non-space, non-punctuation
*
* 3. Subsequent characters must be belong to the alphanumeric characters,
* '_', '.', and '-'.
*
* Names are case insensitive
*
* @param name Name of metric to be created
*/
Meter.prototype._isValidName = function (name) {
return Boolean(name.match(/^[a-z][a-z0-9_.-]{0,62}$/i));
};
return Meter;

@@ -281,0 +72,0 @@ }());

@@ -1,23 +0,92 @@

import * as api from '@opentelemetry/api-metrics';
import * as metrics from '@opentelemetry/api-metrics';
import { Resource } from '@opentelemetry/resources';
import { Meter } from '.';
import { MeterConfig } from './types';
import { MetricReader } from './export/MetricReader';
import { Aggregation } from './view/Aggregation';
import { InstrumentType } from './InstrumentDescriptor';
import { ForceFlushOptions, ShutdownOptions } from './types';
/**
* This class represents a meter provider which platform libraries can extend
* MeterProviderOptions provides an interface for configuring a MeterProvider.
*/
export declare class MeterProvider implements api.MeterProvider {
private readonly _config;
private readonly _meters;
private _shuttingDownPromise;
private _isShutdown;
readonly resource: Resource;
constructor(config?: MeterConfig);
export interface MeterProviderOptions {
/** Resource associated with metric telemetry */
resource?: Resource;
}
export declare type ViewOptions = {
/**
* Returns a Meter, creating one if one with the given name and version is not already created
* If not provided, the Instrument name will be used by default. This will be used as the name of the metrics stream.
*/
name?: string;
/**
* If not provided, the Instrument description will be used by default.
*/
description?: string;
/**
* If provided, the attributes that are not in the list will be ignored.
* If not provided, all the attribute keys will be used by default.
*/
attributeKeys?: string[];
/**
* The {@link Aggregation} aggregation to be used.
*/
aggregation?: Aggregation;
};
export declare type SelectorOptions = {
instrument?: {
/**
* The type of the Instrument(s).
*/
type?: InstrumentType;
/**
* Name of the Instrument(s) with wildcard support.
*/
name?: string;
};
meter?: {
/**
* The name of the Meter.
*/
name?: string;
/**
* The version of the Meter.
*/
version?: string;
/**
* The schema URL of the Meter.
*/
schemaUrl?: string;
};
};
/**
* This class implements the {@link metrics.MeterProvider} interface.
*/
export declare class MeterProvider implements metrics.MeterProvider {
private _sharedState;
private _shutdown;
constructor(options?: MeterProviderOptions);
/**
* Get a meter with the configuration of the MeterProvider.
*/
getMeter(name: string, version?: string, options?: metrics.MeterOptions): metrics.Meter;
/**
* Register a {@link MetricReader} to the meter provider. After the
* registration, the MetricReader can start metrics collection.
*
* @returns Meter A Meter with the given name and version
* @param metricReader the metric reader to be registered.
*/
getMeter(name: string, version?: string, options?: api.MeterOptions): Meter;
shutdown(): Promise<void>;
addMetricReader(metricReader: MetricReader): void;
addView(options: ViewOptions, selectorOptions?: SelectorOptions): void;
/**
* Flush all buffered data and shut down the MeterProvider and all registered
* MetricReaders.
*
* Returns a promise which is resolved when all flushes are complete.
*/
shutdown(options?: ShutdownOptions): Promise<void>;
/**
* Notifies all registered MetricReaders to flush any buffered data.
*
* Returns a promise which is resolved when all flushes are complete.
*/
forceFlush(options?: ForceFlushOptions): Promise<void>;
}
//# sourceMappingURL=MeterProvider.d.ts.map

@@ -16,70 +16,167 @@ /*

*/
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
import * as api from '@opentelemetry/api';
import * as metrics from '@opentelemetry/api-metrics';
import { Resource } from '@opentelemetry/resources';
import { Meter } from '.';
import { DEFAULT_CONFIG } from './types';
// eslint-disable-next-line @typescript-eslint/no-var-requires
var merge = require('lodash.merge');
// @TODO - replace once the core is released
// import { merge } from '@opentelemetry/core';
import { MeterProviderSharedState } from './state/MeterProviderSharedState';
import { InstrumentSelector } from './view/InstrumentSelector';
import { MeterSelector } from './view/MeterSelector';
import { View } from './view/View';
import { MetricCollector } from './state/MetricCollector';
import { FilteringAttributesProcessor } from './view/AttributesProcessor';
import { PatternPredicate } from './view/Predicate';
function isViewOptionsEmpty(options) {
return (options.name == null &&
options.aggregation == null &&
options.attributeKeys == null &&
options.description == null);
}
/**
* This class represents a meter provider which platform libraries can extend
* This class implements the {@link metrics.MeterProvider} interface.
*/
var MeterProvider = /** @class */ (function () {
function MeterProvider(config) {
if (config === void 0) { config = {}; }
this._meters = new Map();
this._shuttingDownPromise = Promise.resolve();
this._isShutdown = false;
var mergedConfig = merge({}, DEFAULT_CONFIG, config);
this.resource = mergedConfig.resource || Resource.empty();
this.resource = Resource.default().merge(this.resource);
this._config = Object.assign({}, mergedConfig, {
resource: this.resource,
});
function MeterProvider(options) {
var _a;
this._shutdown = false;
this._sharedState = new MeterProviderSharedState((_a = options === null || options === void 0 ? void 0 : options.resource) !== null && _a !== void 0 ? _a : Resource.empty());
}
/**
* Returns a Meter, creating one if one with the given name and version is not already created
* Get a meter with the configuration of the MeterProvider.
*/
MeterProvider.prototype.getMeter = function (name, version, options) {
if (version === void 0) { version = ''; }
if (options === void 0) { options = {}; }
// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#meter-creation
if (this._shutdown) {
api.diag.warn('A shutdown MeterProvider cannot provide a Meter');
return metrics.NOOP_METER;
}
return this._sharedState
.getMeterSharedState({ name: name, version: version, schemaUrl: options.schemaUrl })
.meter;
};
/**
* Register a {@link MetricReader} to the meter provider. After the
* registration, the MetricReader can start metrics collection.
*
* @returns Meter A Meter with the given name and version
* @param metricReader the metric reader to be registered.
*/
MeterProvider.prototype.getMeter = function (name, version, options) {
MeterProvider.prototype.addMetricReader = function (metricReader) {
var collector = new MetricCollector(this._sharedState, metricReader);
metricReader.setMetricProducer(collector);
this._sharedState.metricCollectors.push(collector);
};
MeterProvider.prototype.addView = function (options, selectorOptions) {
var _a;
var key = name + "@" + (version !== null && version !== void 0 ? version : '') + ":" + ((_a = options === null || options === void 0 ? void 0 : options.schemaUrl) !== null && _a !== void 0 ? _a : '');
if (!this._meters.has(key)) {
this._meters.set(key, new Meter({
name: name,
version: version,
schemaUrl: options === null || options === void 0 ? void 0 : options.schemaUrl
}, this._config));
if (isViewOptionsEmpty(options)) {
throw new Error('Cannot create view with no view arguments supplied');
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return this._meters.get(key);
// the SDK SHOULD NOT allow Views with a specified name to be declared with instrument selectors that
// may select more than one instrument (e.g. wild card instrument name) in the same Meter.
if (options.name != null &&
(((_a = selectorOptions === null || selectorOptions === void 0 ? void 0 : selectorOptions.instrument) === null || _a === void 0 ? void 0 : _a.name) == null ||
PatternPredicate.hasWildcard(selectorOptions.instrument.name))) {
throw new Error('Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.');
}
// Create AttributesProcessor if attributeKeys are defined set.
var attributesProcessor = undefined;
if (options.attributeKeys != null) {
attributesProcessor = new FilteringAttributesProcessor(options.attributeKeys);
}
var view = new View({
name: options.name,
description: options.description,
aggregation: options.aggregation,
attributesProcessor: attributesProcessor
});
var instrument = new InstrumentSelector(selectorOptions === null || selectorOptions === void 0 ? void 0 : selectorOptions.instrument);
var meter = new MeterSelector(selectorOptions === null || selectorOptions === void 0 ? void 0 : selectorOptions.meter);
this._sharedState.viewRegistry.addView(view, instrument, meter);
};
MeterProvider.prototype.shutdown = function () {
var _this = this;
if (this._isShutdown) {
return this._shuttingDownPromise;
}
this._isShutdown = true;
this._shuttingDownPromise = new Promise(function (resolve, reject) {
Promise.resolve()
.then(function () {
return Promise.all(Array.from(_this._meters, function (_a) {
var _ = _a[0], meter = _a[1];
return meter.shutdown();
}));
})
.then(function () {
if (_this._config.exporter) {
return _this._config.exporter.shutdown();
/**
* Flush all buffered data and shut down the MeterProvider and all registered
* MetricReaders.
*
* Returns a promise which is resolved when all flushes are complete.
*/
MeterProvider.prototype.shutdown = function (options) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (this._shutdown) {
api.diag.warn('shutdown may only be called once per MeterProvider');
return [2 /*return*/];
}
this._shutdown = true;
return [4 /*yield*/, Promise.all(this._sharedState.metricCollectors.map(function (collector) {
return collector.shutdown(options);
}))];
case 1:
_a.sent();
return [2 /*return*/];
}
return;
})
.then(resolve)
.catch(function (e) {
reject(e);
});
});
return this._shuttingDownPromise;
};
/**
* Notifies all registered MetricReaders to flush any buffered data.
*
* Returns a promise which is resolved when all flushes are complete.
*/
MeterProvider.prototype.forceFlush = function (options) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// do not flush after shutdown
if (this._shutdown) {
api.diag.warn('invalid attempt to force flush after MeterProvider shutdown');
return [2 /*return*/];
}
return [4 /*yield*/, Promise.all(this._sharedState.metricCollectors.map(function (collector) {
return collector.forceFlush(options);
}))];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
};
return MeterProvider;

@@ -86,0 +183,0 @@ }());

@@ -1,9 +0,16 @@

import { ObservableResult as TypeObservableResult, Attributes } from '@opentelemetry/api-metrics';
import * as metrics from '@opentelemetry/api-metrics';
import { AttributeHashMap } from './state/HashMap';
/**
* Implementation of {@link TypeObservableResult}
* The class implements {@link metrics.observableResult} interface.
*/
export declare class ObservableResult implements TypeObservableResult {
values: Map<Attributes, number>;
observe(value: number, attributes: Attributes): void;
export declare class ObservableResult implements metrics.ObservableResult {
/**
* @internal
*/
buffer: AttributeHashMap<number>;
/**
* Observe a measurement of the value associated with the given attributes.
*/
observe(value: number, attributes?: metrics.MetricAttributes): void;
}
//# sourceMappingURL=ObservableResult.d.ts.map

@@ -16,11 +16,19 @@ /*

*/
import { AttributeHashMap } from './state/HashMap';
/**
* Implementation of {@link TypeObservableResult}
* The class implements {@link metrics.observableResult} interface.
*/
var ObservableResult = /** @class */ (function () {
function ObservableResult() {
this.values = new Map();
/**
* @internal
*/
this.buffer = new AttributeHashMap();
}
/**
* Observe a measurement of the value associated with the given attributes.
*/
ObservableResult.prototype.observe = function (value, attributes) {
this.values.set(attributes, value);
if (attributes === void 0) { attributes = {}; }
this.buffer.set(attributes, value);
};

@@ -27,0 +35,0 @@ return ObservableResult;

@@ -1,25 +0,7 @@

import * as api from '@opentelemetry/api-metrics';
import { Resource } from '@opentelemetry/resources';
import { Processor } from './export/Processor';
import { MetricExporter } from './export/types';
/** MeterConfig provides an interface for configuring a Meter. */
export interface MeterConfig extends api.MeterOptions {
/** Metric exporter. */
exporter?: MetricExporter;
/** Metric collect interval */
interval?: number;
/** Resource associated with metric telemetry */
resource?: Resource;
/** Metric Processor. */
processor?: Processor;
}
/** Default Meter configuration. */
export declare const DEFAULT_CONFIG: {};
/** The default metric creation options value. */
export declare const DEFAULT_METRIC_OPTIONS: {
disabled: boolean;
description: string;
unit: string;
valueType: api.ValueType;
export declare type CommonReaderOptions = {
timeoutMillis?: number;
};
export declare type CollectionOptions = CommonReaderOptions;
export declare type ShutdownOptions = CommonReaderOptions;
export declare type ForceFlushOptions = CommonReaderOptions;
//# sourceMappingURL=types.d.ts.map

@@ -16,12 +16,3 @@ /*

*/
import * as api from '@opentelemetry/api-metrics';
/** Default Meter configuration. */
export var DEFAULT_CONFIG = {};
/** The default metric creation options value. */
export var DEFAULT_METRIC_OPTIONS = {
disabled: false,
description: '',
unit: '1',
valueType: api.ValueType.DOUBLE,
};
export {};
//# sourceMappingURL=types.js.map

@@ -1,2 +0,2 @@

export declare const VERSION = "0.27.0";
export declare const VERSION = "0.28.0";
//# sourceMappingURL=version.d.ts.map

@@ -17,3 +17,3 @@ /*

// this is autogenerated file, see scripts/version-update.js
export var VERSION = '0.27.0';
export var VERSION = '0.28.0';
//# sourceMappingURL=version.js.map

@@ -1,14 +0,17 @@

export * from './BoundInstrument';
export * from './CounterMetric';
export * from './HistogramMetric';
export { Histogram } from './aggregator/types';
export * from './export/AggregationTemporality';
export * from './export/MetricData';
export { MeterProvider, MeterProviderOptions } from './MeterProvider';
export * from './export/MetricExporter';
export * from './export/MetricProducer';
export * from './export/MetricReader';
export * from './export/PeriodicExportingMetricReader';
export { InstrumentDescriptor, InstrumentType } from './InstrumentDescriptor';
export * from './Meter';
export * from './MeterProvider';
export * from './Metric';
export * from './ObservableGaugeMetric';
export * from './export/aggregators';
export * from './export/ConsoleMetricExporter';
export * from './export/Processor';
export * from './export/types';
export * from './UpDownCounterMetric';
export { MeterConfig } from './types';
export * from './ObservableResult';
export { TimeoutError } from './utils';
export * from './view/Aggregation';
export { FilteringAttributesProcessor } from './view/AttributesProcessor';
export * from './aggregator/types';
//# sourceMappingURL=index.d.ts.map

@@ -28,14 +28,22 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./BoundInstrument"), exports);
__exportStar(require("./CounterMetric"), exports);
__exportStar(require("./HistogramMetric"), exports);
exports.FilteringAttributesProcessor = exports.TimeoutError = exports.InstrumentType = exports.MeterProvider = void 0;
__exportStar(require("./export/AggregationTemporality"), exports);
__exportStar(require("./export/MetricData"), exports);
var MeterProvider_1 = require("./MeterProvider");
Object.defineProperty(exports, "MeterProvider", { enumerable: true, get: function () { return MeterProvider_1.MeterProvider; } });
__exportStar(require("./export/MetricExporter"), exports);
__exportStar(require("./export/MetricProducer"), exports);
__exportStar(require("./export/MetricReader"), exports);
__exportStar(require("./export/PeriodicExportingMetricReader"), exports);
var InstrumentDescriptor_1 = require("./InstrumentDescriptor");
Object.defineProperty(exports, "InstrumentType", { enumerable: true, get: function () { return InstrumentDescriptor_1.InstrumentType; } });
__exportStar(require("./Meter"), exports);
__exportStar(require("./MeterProvider"), exports);
__exportStar(require("./Metric"), exports);
__exportStar(require("./ObservableGaugeMetric"), exports);
__exportStar(require("./export/aggregators"), exports);
__exportStar(require("./export/ConsoleMetricExporter"), exports);
__exportStar(require("./export/Processor"), exports);
__exportStar(require("./export/types"), exports);
__exportStar(require("./UpDownCounterMetric"), exports);
__exportStar(require("./ObservableResult"), exports);
var utils_1 = require("./utils");
Object.defineProperty(exports, "TimeoutError", { enumerable: true, get: function () { return utils_1.TimeoutError; } });
__exportStar(require("./view/Aggregation"), exports);
var AttributesProcessor_1 = require("./view/AttributesProcessor");
Object.defineProperty(exports, "FilteringAttributesProcessor", { enumerable: true, get: function () { return AttributesProcessor_1.FilteringAttributesProcessor; } });
__exportStar(require("./aggregator/types"), exports);
//# sourceMappingURL=index.js.map

@@ -1,92 +0,34 @@

import * as api from '@opentelemetry/api-metrics';
import { InstrumentationLibrary } from '@opentelemetry/core';
import { Processor } from './export/Processor';
import { MeterConfig } from './types';
import * as metrics from '@opentelemetry/api-metrics';
import { MeterSharedState } from './state/MeterSharedState';
/**
* Meter is an implementation of the {@link Meter} interface.
* This class implements the {@link metrics.Meter} interface.
*/
export declare class Meter implements api.Meter {
private readonly _metrics;
private readonly _processor;
private readonly _resource;
private readonly _instrumentationLibrary;
private readonly _controller;
private _isShutdown;
private _shuttingDownPromise;
export declare class Meter implements metrics.Meter {
private _meterSharedState;
constructor(_meterSharedState: MeterSharedState);
/**
* Constructs a new Meter instance.
* Create a {@link metrics.Histogram} instrument.
*/
constructor(instrumentationLibrary: InstrumentationLibrary, config?: MeterConfig);
createHistogram(name: string, options?: metrics.HistogramOptions): metrics.Histogram;
/**
* Creates and returns a new {@link Histogram}.
* @param name the name of the metric.
* @param [options] the metric options.
* Create a {@link metrics.Counter} instrument.
*/
createHistogram(name: string, options?: api.MetricOptions): api.Histogram;
createCounter(name: string, options?: metrics.CounterOptions): metrics.Counter;
/**
* Creates a new counter metric. Generally, this kind of metric when the
* value is a quantity, the sum is of primary interest, and the event count
* and value distribution are not of primary interest.
* @param name the name of the metric.
* @param [options] the metric options.
* Create a {@link metrics.UpDownCounter} instrument.
*/
createCounter(name: string, options?: api.MetricOptions): api.Counter;
createUpDownCounter(name: string, options?: metrics.UpDownCounterOptions): metrics.UpDownCounter;
/**
* Creates a new `UpDownCounter` metric. UpDownCounter is a synchronous
* instrument and very similar to Counter except that Add(increment)
* supports negative increments. It is generally useful for capturing changes
* in an amount of resources used, or any quantity that rises and falls
* during a request.
*
* @param name the name of the metric.
* @param [options] the metric options.
* Create a ObservableGauge instrument.
*/
createUpDownCounter(name: string, options?: api.MetricOptions): api.UpDownCounter;
createObservableGauge(name: string, callback: metrics.ObservableCallback, options?: metrics.ObservableGaugeOptions): void;
/**
* Creates a new `ObservableGauge` metric.
* @param name the name of the metric.
* @param [options] the metric options.
* @param [callback] the observable gauge callback
* Create a ObservableCounter instrument.
*/
createObservableGauge(name: string, options?: api.MetricOptions, callback?: (observableResult: api.ObservableResult) => unknown): api.ObservableGauge;
createObservableCounter(name: string, options?: api.MetricOptions, callback?: (observableResult: api.ObservableResult) => unknown): api.ObservableCounter;
createObservableCounter(name: string, callback: metrics.ObservableCallback, options?: metrics.ObservableCounterOptions): void;
/**
* Creates a new `ObservableUpDownCounter` metric.
* @param name the name of the metric.
* @param [options] the metric options.
* @param [callback] the observable gauge callback
* Create a ObservableUpDownCounter instrument.
*/
createObservableUpDownCounter(name: string, options?: api.MetricOptions, callback?: (observableResult: api.ObservableResult) => unknown): api.ObservableUpDownCounter;
/**
* Collects all the metrics created with this `Meter` for export.
*
* Utilizes the processor to create checkpoints of the current values in
* each aggregator belonging to the metrics that were created with this
* meter instance.
*/
collect(): Promise<void>;
getProcessor(): Processor;
shutdown(): Promise<void>;
/**
* Registers metric to register.
* @param name The name of the metric.
* @param metric The metric to register.
*/
private _registerMetric;
/**
* Ensure a metric name conforms to the following rules:
*
* 1. They are non-empty strings
*
* 2. The first character must be non-numeric, non-space, non-punctuation
*
* 3. Subsequent characters must be belong to the alphanumeric characters,
* '_', '.', and '-'.
*
* Names are case insensitive
*
* @param name Name of metric to be created
*/
private _isValidName;
createObservableUpDownCounter(name: string, callback: metrics.ObservableCallback, options?: metrics.ObservableUpDownCounterOptions): void;
}
//# sourceMappingURL=Meter.d.ts.map

@@ -19,204 +19,58 @@ "use strict";

exports.Meter = void 0;
const api_1 = require("@opentelemetry/api");
const api = require("@opentelemetry/api-metrics");
const resources_1 = require("@opentelemetry/resources");
const CounterMetric_1 = require("./CounterMetric");
const Controller_1 = require("./export/Controller");
const NoopExporter_1 = require("./export/NoopExporter");
const Processor_1 = require("./export/Processor");
const ObservableCounterMetric_1 = require("./ObservableCounterMetric");
const types_1 = require("./types");
const UpDownCounterMetric_1 = require("./UpDownCounterMetric");
const ObservableUpDownCounterMetric_1 = require("./ObservableUpDownCounterMetric");
const ObservableGaugeMetric_1 = require("./ObservableGaugeMetric");
const HistogramMetric_1 = require("./HistogramMetric");
// eslint-disable-next-line @typescript-eslint/no-var-requires
const merge = require('lodash.merge');
// @TODO - replace once the core is released
// import { merge } from '@opentelemetry/core';
const InstrumentDescriptor_1 = require("./InstrumentDescriptor");
const Instruments_1 = require("./Instruments");
/**
* Meter is an implementation of the {@link Meter} interface.
* This class implements the {@link metrics.Meter} interface.
*/
class Meter {
/**
* Constructs a new Meter instance.
*/
constructor(instrumentationLibrary, config = {}) {
var _a;
this._metrics = new Map();
this._isShutdown = false;
this._shuttingDownPromise = Promise.resolve();
const mergedConfig = merge({}, types_1.DEFAULT_CONFIG, config);
this._processor = (_a = mergedConfig.processor) !== null && _a !== void 0 ? _a : new Processor_1.UngroupedProcessor();
this._resource =
mergedConfig.resource || resources_1.Resource.empty();
this._instrumentationLibrary = instrumentationLibrary;
// start the push controller
const exporter = mergedConfig.exporter || new NoopExporter_1.NoopExporter();
const interval = mergedConfig.interval;
this._controller = new Controller_1.PushController(this, exporter, interval);
constructor(_meterSharedState) {
this._meterSharedState = _meterSharedState;
}
/**
* Creates and returns a new {@link Histogram}.
* @param name the name of the metric.
* @param [options] the metric options.
* Create a {@link metrics.Histogram} instrument.
*/
createHistogram(name, options) {
if (!this._isValidName(name)) {
api_1.diag.warn(`Invalid metric name ${name}. Defaulting to noop metric implementation.`);
return api.NOOP_HISTOGRAM_METRIC;
}
const opt = Object.assign(Object.assign({}, types_1.DEFAULT_METRIC_OPTIONS), options);
const histogram = new HistogramMetric_1.HistogramMetric(name, opt, this._processor, this._resource, this._instrumentationLibrary);
this._registerMetric(name, histogram);
return histogram;
const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, InstrumentDescriptor_1.InstrumentType.HISTOGRAM, options);
const storage = this._meterSharedState.registerMetricStorage(descriptor);
return new Instruments_1.HistogramInstrument(storage, descriptor);
}
/**
* Creates a new counter metric. Generally, this kind of metric when the
* value is a quantity, the sum is of primary interest, and the event count
* and value distribution are not of primary interest.
* @param name the name of the metric.
* @param [options] the metric options.
* Create a {@link metrics.Counter} instrument.
*/
createCounter(name, options) {
if (!this._isValidName(name)) {
api_1.diag.warn(`Invalid metric name ${name}. Defaulting to noop metric implementation.`);
return api.NOOP_COUNTER_METRIC;
}
const opt = Object.assign(Object.assign({}, types_1.DEFAULT_METRIC_OPTIONS), options);
const counter = new CounterMetric_1.CounterMetric(name, opt, this._processor, this._resource, this._instrumentationLibrary);
this._registerMetric(name, counter);
return counter;
const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, InstrumentDescriptor_1.InstrumentType.COUNTER, options);
const storage = this._meterSharedState.registerMetricStorage(descriptor);
return new Instruments_1.CounterInstrument(storage, descriptor);
}
/**
* Creates a new `UpDownCounter` metric. UpDownCounter is a synchronous
* instrument and very similar to Counter except that Add(increment)
* supports negative increments. It is generally useful for capturing changes
* in an amount of resources used, or any quantity that rises and falls
* during a request.
*
* @param name the name of the metric.
* @param [options] the metric options.
* Create a {@link metrics.UpDownCounter} instrument.
*/
createUpDownCounter(name, options) {
if (!this._isValidName(name)) {
api_1.diag.warn(`Invalid metric name ${name}. Defaulting to noop metric implementation.`);
return api.NOOP_COUNTER_METRIC;
}
const opt = Object.assign(Object.assign({}, types_1.DEFAULT_METRIC_OPTIONS), options);
const upDownCounter = new UpDownCounterMetric_1.UpDownCounterMetric(name, opt, this._processor, this._resource, this._instrumentationLibrary);
this._registerMetric(name, upDownCounter);
return upDownCounter;
const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, InstrumentDescriptor_1.InstrumentType.UP_DOWN_COUNTER, options);
const storage = this._meterSharedState.registerMetricStorage(descriptor);
return new Instruments_1.UpDownCounterInstrument(storage, descriptor);
}
/**
* Creates a new `ObservableGauge` metric.
* @param name the name of the metric.
* @param [options] the metric options.
* @param [callback] the observable gauge callback
* Create a ObservableGauge instrument.
*/
createObservableGauge(name, options = {}, callback) {
if (!this._isValidName(name)) {
api_1.diag.warn(`Invalid metric name ${name}. Defaulting to noop metric implementation.`);
return api.NOOP_OBSERVABLE_GAUGE_METRIC;
}
const opt = Object.assign(Object.assign({}, types_1.DEFAULT_METRIC_OPTIONS), options);
const observableGauge = new ObservableGaugeMetric_1.ObservableGaugeMetric(name, opt, this._processor, this._resource, this._instrumentationLibrary, callback);
this._registerMetric(name, observableGauge);
return observableGauge;
createObservableGauge(name, callback, options) {
const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, InstrumentDescriptor_1.InstrumentType.OBSERVABLE_GAUGE, options);
this._meterSharedState.registerAsyncMetricStorage(descriptor, callback);
}
createObservableCounter(name, options = {}, callback) {
if (!this._isValidName(name)) {
api_1.diag.warn(`Invalid metric name ${name}. Defaulting to noop metric implementation.`);
return api.NOOP_OBSERVABLE_COUNTER_METRIC;
}
const opt = Object.assign(Object.assign({}, types_1.DEFAULT_METRIC_OPTIONS), options);
const observableCounter = new ObservableCounterMetric_1.ObservableCounterMetric(name, opt, this._processor, this._resource, this._instrumentationLibrary, callback);
this._registerMetric(name, observableCounter);
return observableCounter;
}
/**
* Creates a new `ObservableUpDownCounter` metric.
* @param name the name of the metric.
* @param [options] the metric options.
* @param [callback] the observable gauge callback
* Create a ObservableCounter instrument.
*/
createObservableUpDownCounter(name, options = {}, callback) {
if (!this._isValidName(name)) {
api_1.diag.warn(`Invalid metric name ${name}. Defaulting to noop metric implementation.`);
return api.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC;
}
const opt = Object.assign(Object.assign({}, types_1.DEFAULT_METRIC_OPTIONS), options);
const observableUpDownCounter = new ObservableUpDownCounterMetric_1.ObservableUpDownCounterMetric(name, opt, this._processor, this._resource, this._instrumentationLibrary, callback);
this._registerMetric(name, observableUpDownCounter);
return observableUpDownCounter;
createObservableCounter(name, callback, options) {
const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, InstrumentDescriptor_1.InstrumentType.OBSERVABLE_COUNTER, options);
this._meterSharedState.registerAsyncMetricStorage(descriptor, callback);
}
/**
* Collects all the metrics created with this `Meter` for export.
*
* Utilizes the processor to create checkpoints of the current values in
* each aggregator belonging to the metrics that were created with this
* meter instance.
* Create a ObservableUpDownCounter instrument.
*/
async collect() {
// after this all remaining metrics can be run
const metricsRecords = Array.from(this._metrics.values()).map(metric => {
return metric.getMetricRecord();
});
await Promise.all(metricsRecords).then(records => {
records.forEach(metrics => {
metrics.forEach(metric => this._processor.process(metric));
});
});
createObservableUpDownCounter(name, callback, options) {
const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, InstrumentDescriptor_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER, options);
this._meterSharedState.registerAsyncMetricStorage(descriptor, callback);
}
getProcessor() {
return this._processor;
}
shutdown() {
if (this._isShutdown) {
return this._shuttingDownPromise;
}
this._isShutdown = true;
this._shuttingDownPromise = new Promise((resolve, reject) => {
Promise.resolve()
.then(() => {
return this._controller.shutdown();
})
.then(resolve)
.catch(e => {
reject(e);
});
});
return this._shuttingDownPromise;
}
/**
* Registers metric to register.
* @param name The name of the metric.
* @param metric The metric to register.
*/
_registerMetric(name, metric) {
if (this._metrics.has(name)) {
api_1.diag.error(`A metric with the name ${name} has already been registered.`);
return;
}
this._metrics.set(name, metric);
}
/**
* Ensure a metric name conforms to the following rules:
*
* 1. They are non-empty strings
*
* 2. The first character must be non-numeric, non-space, non-punctuation
*
* 3. Subsequent characters must be belong to the alphanumeric characters,
* '_', '.', and '-'.
*
* Names are case insensitive
*
* @param name Name of metric to be created
*/
_isValidName(name) {
return Boolean(name.match(/^[a-z][a-z0-9_.-]{0,62}$/i));
}
}
exports.Meter = Meter;
//# sourceMappingURL=Meter.js.map

@@ -1,23 +0,92 @@

import * as api from '@opentelemetry/api-metrics';
import * as metrics from '@opentelemetry/api-metrics';
import { Resource } from '@opentelemetry/resources';
import { Meter } from '.';
import { MeterConfig } from './types';
import { MetricReader } from './export/MetricReader';
import { Aggregation } from './view/Aggregation';
import { InstrumentType } from './InstrumentDescriptor';
import { ForceFlushOptions, ShutdownOptions } from './types';
/**
* This class represents a meter provider which platform libraries can extend
* MeterProviderOptions provides an interface for configuring a MeterProvider.
*/
export declare class MeterProvider implements api.MeterProvider {
private readonly _config;
private readonly _meters;
private _shuttingDownPromise;
private _isShutdown;
readonly resource: Resource;
constructor(config?: MeterConfig);
export interface MeterProviderOptions {
/** Resource associated with metric telemetry */
resource?: Resource;
}
export declare type ViewOptions = {
/**
* Returns a Meter, creating one if one with the given name and version is not already created
* If not provided, the Instrument name will be used by default. This will be used as the name of the metrics stream.
*/
name?: string;
/**
* If not provided, the Instrument description will be used by default.
*/
description?: string;
/**
* If provided, the attributes that are not in the list will be ignored.
* If not provided, all the attribute keys will be used by default.
*/
attributeKeys?: string[];
/**
* The {@link Aggregation} aggregation to be used.
*/
aggregation?: Aggregation;
};
export declare type SelectorOptions = {
instrument?: {
/**
* The type of the Instrument(s).
*/
type?: InstrumentType;
/**
* Name of the Instrument(s) with wildcard support.
*/
name?: string;
};
meter?: {
/**
* The name of the Meter.
*/
name?: string;
/**
* The version of the Meter.
*/
version?: string;
/**
* The schema URL of the Meter.
*/
schemaUrl?: string;
};
};
/**
* This class implements the {@link metrics.MeterProvider} interface.
*/
export declare class MeterProvider implements metrics.MeterProvider {
private _sharedState;
private _shutdown;
constructor(options?: MeterProviderOptions);
/**
* Get a meter with the configuration of the MeterProvider.
*/
getMeter(name: string, version?: string, options?: metrics.MeterOptions): metrics.Meter;
/**
* Register a {@link MetricReader} to the meter provider. After the
* registration, the MetricReader can start metrics collection.
*
* @returns Meter A Meter with the given name and version
* @param metricReader the metric reader to be registered.
*/
getMeter(name: string, version?: string, options?: api.MeterOptions): Meter;
shutdown(): Promise<void>;
addMetricReader(metricReader: MetricReader): void;
addView(options: ViewOptions, selectorOptions?: SelectorOptions): void;
/**
* Flush all buffered data and shut down the MeterProvider and all registered
* MetricReaders.
*
* Returns a promise which is resolved when all flushes are complete.
*/
shutdown(options?: ShutdownOptions): Promise<void>;
/**
* Notifies all registered MetricReaders to flush any buffered data.
*
* Returns a promise which is resolved when all flushes are complete.
*/
forceFlush(options?: ForceFlushOptions): Promise<void>;
}
//# sourceMappingURL=MeterProvider.d.ts.map

@@ -19,67 +19,111 @@ "use strict";

exports.MeterProvider = void 0;
const api = require("@opentelemetry/api");
const metrics = require("@opentelemetry/api-metrics");
const resources_1 = require("@opentelemetry/resources");
const _1 = require(".");
const types_1 = require("./types");
// eslint-disable-next-line @typescript-eslint/no-var-requires
const merge = require('lodash.merge');
// @TODO - replace once the core is released
// import { merge } from '@opentelemetry/core';
const MeterProviderSharedState_1 = require("./state/MeterProviderSharedState");
const InstrumentSelector_1 = require("./view/InstrumentSelector");
const MeterSelector_1 = require("./view/MeterSelector");
const View_1 = require("./view/View");
const MetricCollector_1 = require("./state/MetricCollector");
const AttributesProcessor_1 = require("./view/AttributesProcessor");
const Predicate_1 = require("./view/Predicate");
function isViewOptionsEmpty(options) {
return (options.name == null &&
options.aggregation == null &&
options.attributeKeys == null &&
options.description == null);
}
/**
* This class represents a meter provider which platform libraries can extend
* This class implements the {@link metrics.MeterProvider} interface.
*/
class MeterProvider {
constructor(config = {}) {
this._meters = new Map();
this._shuttingDownPromise = Promise.resolve();
this._isShutdown = false;
const mergedConfig = merge({}, types_1.DEFAULT_CONFIG, config);
this.resource = mergedConfig.resource || resources_1.Resource.empty();
this.resource = resources_1.Resource.default().merge(this.resource);
this._config = Object.assign({}, mergedConfig, {
resource: this.resource,
});
constructor(options) {
var _a;
this._shutdown = false;
this._sharedState = new MeterProviderSharedState_1.MeterProviderSharedState((_a = options === null || options === void 0 ? void 0 : options.resource) !== null && _a !== void 0 ? _a : resources_1.Resource.empty());
}
/**
* Returns a Meter, creating one if one with the given name and version is not already created
* Get a meter with the configuration of the MeterProvider.
*/
getMeter(name, version = '', options = {}) {
// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#meter-creation
if (this._shutdown) {
api.diag.warn('A shutdown MeterProvider cannot provide a Meter');
return metrics.NOOP_METER;
}
return this._sharedState
.getMeterSharedState({ name, version, schemaUrl: options.schemaUrl })
.meter;
}
/**
* Register a {@link MetricReader} to the meter provider. After the
* registration, the MetricReader can start metrics collection.
*
* @returns Meter A Meter with the given name and version
* @param metricReader the metric reader to be registered.
*/
getMeter(name, version, options) {
addMetricReader(metricReader) {
const collector = new MetricCollector_1.MetricCollector(this._sharedState, metricReader);
metricReader.setMetricProducer(collector);
this._sharedState.metricCollectors.push(collector);
}
addView(options, selectorOptions) {
var _a;
const key = `${name}@${version !== null && version !== void 0 ? version : ''}:${(_a = options === null || options === void 0 ? void 0 : options.schemaUrl) !== null && _a !== void 0 ? _a : ''}`;
if (!this._meters.has(key)) {
this._meters.set(key, new _1.Meter({
name,
version,
schemaUrl: options === null || options === void 0 ? void 0 : options.schemaUrl
}, this._config));
if (isViewOptionsEmpty(options)) {
throw new Error('Cannot create view with no view arguments supplied');
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return this._meters.get(key);
}
shutdown() {
if (this._isShutdown) {
return this._shuttingDownPromise;
// the SDK SHOULD NOT allow Views with a specified name to be declared with instrument selectors that
// may select more than one instrument (e.g. wild card instrument name) in the same Meter.
if (options.name != null &&
(((_a = selectorOptions === null || selectorOptions === void 0 ? void 0 : selectorOptions.instrument) === null || _a === void 0 ? void 0 : _a.name) == null ||
Predicate_1.PatternPredicate.hasWildcard(selectorOptions.instrument.name))) {
throw new Error('Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.');
}
this._isShutdown = true;
this._shuttingDownPromise = new Promise((resolve, reject) => {
Promise.resolve()
.then(() => {
return Promise.all(Array.from(this._meters, ([_, meter]) => meter.shutdown()));
})
.then(() => {
if (this._config.exporter) {
return this._config.exporter.shutdown();
}
return;
})
.then(resolve)
.catch(e => {
reject(e);
});
// Create AttributesProcessor if attributeKeys are defined set.
let attributesProcessor = undefined;
if (options.attributeKeys != null) {
attributesProcessor = new AttributesProcessor_1.FilteringAttributesProcessor(options.attributeKeys);
}
const view = new View_1.View({
name: options.name,
description: options.description,
aggregation: options.aggregation,
attributesProcessor: attributesProcessor
});
return this._shuttingDownPromise;
const instrument = new InstrumentSelector_1.InstrumentSelector(selectorOptions === null || selectorOptions === void 0 ? void 0 : selectorOptions.instrument);
const meter = new MeterSelector_1.MeterSelector(selectorOptions === null || selectorOptions === void 0 ? void 0 : selectorOptions.meter);
this._sharedState.viewRegistry.addView(view, instrument, meter);
}
/**
* Flush all buffered data and shut down the MeterProvider and all registered
* MetricReaders.
*
* Returns a promise which is resolved when all flushes are complete.
*/
async shutdown(options) {
if (this._shutdown) {
api.diag.warn('shutdown may only be called once per MeterProvider');
return;
}
this._shutdown = true;
await Promise.all(this._sharedState.metricCollectors.map(collector => {
return collector.shutdown(options);
}));
}
/**
* Notifies all registered MetricReaders to flush any buffered data.
*
* Returns a promise which is resolved when all flushes are complete.
*/
async forceFlush(options) {
// do not flush after shutdown
if (this._shutdown) {
api.diag.warn('invalid attempt to force flush after MeterProvider shutdown');
return;
}
await Promise.all(this._sharedState.metricCollectors.map(collector => {
return collector.forceFlush(options);
}));
}
}
exports.MeterProvider = MeterProvider;
//# sourceMappingURL=MeterProvider.js.map

@@ -1,9 +0,16 @@

import { ObservableResult as TypeObservableResult, Attributes } from '@opentelemetry/api-metrics';
import * as metrics from '@opentelemetry/api-metrics';
import { AttributeHashMap } from './state/HashMap';
/**
* Implementation of {@link TypeObservableResult}
* The class implements {@link metrics.observableResult} interface.
*/
export declare class ObservableResult implements TypeObservableResult {
values: Map<Attributes, number>;
observe(value: number, attributes: Attributes): void;
export declare class ObservableResult implements metrics.ObservableResult {
/**
* @internal
*/
buffer: AttributeHashMap<number>;
/**
* Observe a measurement of the value associated with the given attributes.
*/
observe(value: number, attributes?: metrics.MetricAttributes): void;
}
//# sourceMappingURL=ObservableResult.d.ts.map

@@ -19,11 +19,18 @@ "use strict";

exports.ObservableResult = void 0;
const HashMap_1 = require("./state/HashMap");
/**
* Implementation of {@link TypeObservableResult}
* The class implements {@link metrics.observableResult} interface.
*/
class ObservableResult {
constructor() {
this.values = new Map();
/**
* @internal
*/
this.buffer = new HashMap_1.AttributeHashMap();
}
observe(value, attributes) {
this.values.set(attributes, value);
/**
* Observe a measurement of the value associated with the given attributes.
*/
observe(value, attributes = {}) {
this.buffer.set(attributes, value);
}

@@ -30,0 +37,0 @@ }

@@ -1,25 +0,7 @@

import * as api from '@opentelemetry/api-metrics';
import { Resource } from '@opentelemetry/resources';
import { Processor } from './export/Processor';
import { MetricExporter } from './export/types';
/** MeterConfig provides an interface for configuring a Meter. */
export interface MeterConfig extends api.MeterOptions {
/** Metric exporter. */
exporter?: MetricExporter;
/** Metric collect interval */
interval?: number;
/** Resource associated with metric telemetry */
resource?: Resource;
/** Metric Processor. */
processor?: Processor;
}
/** Default Meter configuration. */
export declare const DEFAULT_CONFIG: {};
/** The default metric creation options value. */
export declare const DEFAULT_METRIC_OPTIONS: {
disabled: boolean;
description: string;
unit: string;
valueType: api.ValueType;
export declare type CommonReaderOptions = {
timeoutMillis?: number;
};
export declare type CollectionOptions = CommonReaderOptions;
export declare type ShutdownOptions = CommonReaderOptions;
export declare type ForceFlushOptions = CommonReaderOptions;
//# sourceMappingURL=types.d.ts.map

@@ -18,13 +18,2 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.DEFAULT_METRIC_OPTIONS = exports.DEFAULT_CONFIG = void 0;
const api = require("@opentelemetry/api-metrics");
/** Default Meter configuration. */
exports.DEFAULT_CONFIG = {};
/** The default metric creation options value. */
exports.DEFAULT_METRIC_OPTIONS = {
disabled: false,
description: '',
unit: '1',
valueType: api.ValueType.DOUBLE,
};
//# sourceMappingURL=types.js.map

@@ -1,2 +0,2 @@

export declare const VERSION = "0.27.0";
export declare const VERSION = "0.28.0";
//# sourceMappingURL=version.d.ts.map

@@ -20,3 +20,3 @@ "use strict";

// this is autogenerated file, see scripts/version-update.js
exports.VERSION = '0.27.0';
exports.VERSION = '0.28.0';
//# sourceMappingURL=version.js.map
{
"name": "@opentelemetry/sdk-metrics-base",
"version": "0.27.0",
"description": "OpenTelemetry metrics SDK",
"version": "0.28.0",
"description": "Work in progress OpenTelemetry metrics SDK",
"main": "build/src/index.js",
"module": "build/esm/index.js",
"esnext": "build/esnext/index.js",
"types": "build/src/index.d.ts",
"repository": "open-telemetry/opentelemetry-js",
"scripts": {
"compile": "tsc --build tsconfig.json tsconfig.esm.json",
"clean": "tsc --build --clean tsconfig.json tsconfig.esm.json",
"prepublishOnly": "npm run compile",
"compile": "tsc --build tsconfig.all.json",
"clean": "tsc --build --clean tsconfig.all.json",
"test": "nyc ts-mocha -p tsconfig.json 'test/**/*.test.ts'",
"test:browser": "nyc karma start --single-run",
"tdd": "npm run test -- --watch-extensions ts --watch",
"codecov": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../",
"tdd:browser": "karma start",
"codecov": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../../",
"lint": "eslint . --ext .ts",
"lint:fix": "eslint . --ext .ts --fix",
"version": "node ../../../scripts/version-update.js",
"watch": "tsc --build --watch tsconfig.json tsconfig.esm.json",
"precompile": "lerna run version --scope $(npm pkg get name) --include-filtered-dependencies",
"prewatch": "node ../../../scripts/version-update.js"
"watch": "tsc --build --watch tsconfig.all.json",
"precompile": "lerna run version --scope $(npm pkg get name) --include-dependencies",
"prewatch": "node ../../../scripts/version-update.js",
"peer-api-check": "node ../../../scripts/peer-api-check.js"
},

@@ -32,3 +37,3 @@ "keywords": [

"engines": {
"node": ">=8.0.0"
"node": ">=8.12.0"
},

@@ -39,2 +44,5 @@ "files": [

"build/esm/**/*.d.ts",
"build/esnext/**/*.js",
"build/esnext/**/*.js.map",
"build/esnext/**/*.d.ts",
"build/src/**/*.js",

@@ -51,14 +59,20 @@ "build/src/**/*.js.map",

"devDependencies": {
"@opentelemetry/api": "^1.0.3",
"@opentelemetry/api": "^1.0.0",
"@types/lodash.merge": "4.6.6",
"@types/mocha": "8.2.3",
"@types/node": "14.17.11",
"@types/sinon": "10.0.2",
"@types/node": "14.17.33",
"@types/sinon": "10.0.6",
"codecov": "3.8.3",
"karma": "6.3.16",
"karma-chrome-launcher": "3.1.0",
"karma-coverage-istanbul-reporter": "3.0.3",
"karma-mocha": "2.0.1",
"karma-spec-reporter": "0.0.32",
"karma-webpack": "4.0.2",
"mocha": "7.2.0",
"nyc": "15.1.0",
"rimraf": "3.0.2",
"sinon": "12.0.1",
"sinon": "11.1.2",
"ts-mocha": "8.0.0",
"typescript": "4.3.5"
"typescript": "4.4.4"
},

@@ -69,8 +83,8 @@ "peerDependencies": {

"dependencies": {
"@opentelemetry/api-metrics": "0.27.0",
"@opentelemetry/core": "1.0.1",
"@opentelemetry/resources": "1.0.1",
"lodash.merge": "^4.6.2"
"@opentelemetry/api-metrics": "0.28.0",
"@opentelemetry/core": "1.2.0",
"@opentelemetry/resources": "1.2.0",
"lodash.merge": "4.6.2"
},
"gitHead": "f5e227f0cb829df1ca2dc220a3e0e8ae0e607405"
"gitHead": "28a177ffe3950c5602a91391af582a7a8c813c7d"
}
# OpenTelemetry Metrics SDK
[![NPM Published Version][npm-img]][npm-url]
[![dependencies][dependencies-image]][dependencies-url]
[![devDependencies][devDependencies-image]][devDependencies-url]
[![Apache License][license-image]][license-image]

@@ -10,6 +8,10 @@

## Work In Progress
The OpenTelemetry SDK in this directory is undergoing drastic changes. If you need to use metrics, we recommend you use [version `0.27.0`](https://github.com/open-telemetry/opentelemetry-js/tree/experimental/v0.27.0/experimental/packages/opentelemetry-sdk-metrics-base).
## Installation
```bash
npm install --save @opentelemetry/sdk-metrics-base
npm install --save "@opentelemetry/sdk-metrics-base@~0.27.0"
```

@@ -19,176 +21,6 @@

### Counter
Please see the [version `0.27.0` README](https://github.com/open-telemetry/opentelemetry-js/tree/experimental/v0.27.0/experimental/packages/opentelemetry-sdk-metrics-base#usage).
Choose this kind of metric when the value is a quantity, the sum is of primary interest, and the event count and value distribution are not of primary interest. It is restricted to non-negative increments.
Example uses for Counter:
TODO: Add usage information for updated SDK
- count the number of bytes received
- count the number of requests completed
- count the number of accounts created
- count the number of checkpoints run
- count the number of 5xx errors.
```js
const { MeterProvider } = require('@opentelemetry/sdk-metrics-base');
// Initialize the Meter to capture measurements in various ways.
const meter = new MeterProvider().getMeter('your-meter-name');
const counter = meter.createCounter('metric_name', {
description: 'Example of a counter'
});
const attributes = { pid: process.pid };
counter.add(10, attributes);
```
### UpDownCounter
`UpDownCounter` is similar to `Counter` except that it supports negative increments. It is generally useful for capturing changes in an amount of resources used, or any quantity that rises and falls during a request.
Example uses for UpDownCounter:
- count the number of active requests
- count memory in use by instrumenting new and delete
- count queue size by instrumenting enqueue and dequeue
- count semaphore up and down operations
```js
const { MeterProvider } = require('@opentelemetry/sdk-metrics-base');
// Initialize the Meter to capture measurements in various ways.
const meter = new MeterProvider().getMeter('your-meter-name');
const counter = meter.createUpDownCounter('metric_name', {
description: 'Example of a UpDownCounter'
});
const attributes = { pid: process.pid };
counter.add(Math.random() > 0.5 ? 1 : -1, attributes);
```
### Observable Gauge
Choose this kind of metric when only last value is important without worry about aggregation.
The callback can be sync or async.
```js
const { MeterProvider } = require('@opentelemetry/sdk-metrics-base');
const meter = new MeterProvider().getMeter('your-meter-name');
// async callback - for operation that needs to wait for value
meter.createObservableGauge('your_metric_name', {
description: 'Example of an async observable gauge with callback',
}, async (observableResult) => {
const value = await getAsyncValue();
observableResult.observe(value, { attribute: '1' });
});
function getAsyncValue() {
return new Promise((resolve) => {
setTimeout(()=> {
resolve(Math.random());
}, 100);
});
}
// sync callback in case you don't need to wait for value
meter.createObservableGauge('your_metric_name', {
description: 'Example of a sync observable gauge with callback',
}, (observableResult) => {
observableResult.observe(getRandomValue(), { attribute: '1' });
observableResult.observe(getRandomValue(), { attribute: '2' });
});
function getRandomValue() {
return Math.random();
}
```
### ObservableUpDownCounter
Choose this kind of metric when sum is important and you want to capture any value that starts at zero and rises or falls throughout the process lifetime.
The callback can be sync or async.
```js
const { MeterProvider } = require('@opentelemetry/sdk-metrics-base');
const meter = new MeterProvider().getMeter('your-meter-name');
// async callback - for operation that needs to wait for value
meter.createObservableUpDownCounter('your_metric_name', {
description: 'Example of an async observable up down counter with callback',
}, async (observableResult) => {
const value = await getAsyncValue();
observableResult.observe(value, { attribute: '1' });
});
function getAsyncValue() {
return new Promise((resolve) => {
setTimeout(()=> {
resolve(Math.random());
}, 100);
});
}
// sync callback in case you don't need to wait for value
meter.createObservableUpDownCounter('your_metric_name', {
description: 'Example of a sync observable up down counter with callback',
}, (observableResult) => {
observableResult.observe(getRandomValue(), { attribute: '1' });
});
function getRandomValue() {
return Math.random();
}
```
### Observable Counter
Choose this kind of metric when collecting a sum that never decreases.
The callback can be sync or async.
```js
const { MeterProvider } = require('@opentelemetry/sdk-metrics-base');
const meter = new MeterProvider().getMeter('your-meter-name');
// async callback in case you need to wait for values
meter.createObservableCounter('example_metric', {
description: 'Example of an async observable counter with callback',
}, async (observableResult) => {
const value = await getAsyncValue();
observableResult.observe(value, { attribute: '1' });
});
function getAsyncValue() {
return new Promise((resolve) => {
setTimeout(() => {
resolve(Math.random());
}, 100)
});
}
// sync callback in case you don't need to wait for values
meter.createObservableCounter('example_metric', {
description: 'Example of a sync observable counter with callback',
}, (observableResult) => {
const value = getRandomValue();
observableResult.observe(value, { attribute: '1' });
});
function getRandomValue() {
return Math.random();
}
```
### Histogram
`Histogram` is a non-additive synchronous instrument useful for recording any non-additive number, positive or negative.
Values captured by `Histogram.record(value)` are treated as individual events belonging to a distribution that is being summarized.
`Histogram` should be chosen either when capturing measurements that do not contribute meaningfully to a sum, or when capturing numbers that are additive in nature, but where the distribution of individual increments is considered interesting.
## Useful links

@@ -207,7 +39,3 @@

[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat
[dependencies-image]: https://status.david-dm.org/gh/open-telemetry/opentelemetry-js.svg?path=packages%2Fopentelemetry-sdk-metrics-base
[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-metrsics
[devDependencies-image]: https://status.david-dm.org/gh/open-telemetry/opentelemetry-js.svg?path=packages%2Fopentelemetry-sdk-metrics-base&type=dev
[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-sdk-metrics-base&type=dev
[npm-url]: https://www.npmjs.com/package/@opentelemetry/sdk-metrics-base
[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Fsdk-metrics-base.svg
[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Fmetrics.svg

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc