2024-05-08 16:20:31 +08:00
|
|
|
import { Registry } from '@tachybase/utils';
|
2024-05-24 13:06:59 +08:00
|
|
|
|
|
|
|
import opentelemetry from '@opentelemetry/api';
|
|
|
|
import { Resource } from '@opentelemetry/resources';
|
2024-01-02 12:17:46 +08:00
|
|
|
import {
|
|
|
|
ConsoleMetricExporter,
|
|
|
|
MeterProvider,
|
2024-05-24 13:06:59 +08:00
|
|
|
MetricReader,
|
|
|
|
PeriodicExportingMetricReader,
|
2024-01-02 12:17:46 +08:00
|
|
|
View,
|
|
|
|
} from '@opentelemetry/sdk-metrics';
|
|
|
|
|
|
|
|
export type MetricOptions = {
|
|
|
|
meterName?: string;
|
|
|
|
version?: string;
|
|
|
|
readerName?: string | string[];
|
|
|
|
};
|
|
|
|
|
|
|
|
type GetMetricReader = () => MetricReader;
|
|
|
|
|
|
|
|
export class Metric {
|
|
|
|
meterName: string;
|
|
|
|
version: string;
|
|
|
|
readerName: string | string[];
|
|
|
|
readers = new Registry<GetMetricReader>();
|
|
|
|
provider: MeterProvider;
|
|
|
|
views: View[] = [];
|
|
|
|
|
|
|
|
constructor(options?: MetricOptions) {
|
|
|
|
const { meterName, readerName, version } = options || {};
|
|
|
|
this.readerName = readerName || 'console';
|
2024-05-24 13:06:59 +08:00
|
|
|
this.meterName = meterName || 'tachybase-meter';
|
2024-01-02 12:17:46 +08:00
|
|
|
this.version = version || '';
|
|
|
|
this.registerReader(
|
|
|
|
'console',
|
|
|
|
() =>
|
|
|
|
new PeriodicExportingMetricReader({
|
|
|
|
exporter: new ConsoleMetricExporter(),
|
|
|
|
}),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
init(resource: Resource) {
|
|
|
|
this.provider = new MeterProvider({ resource, views: this.views });
|
|
|
|
opentelemetry.metrics.setGlobalMeterProvider(this.provider);
|
|
|
|
}
|
|
|
|
|
|
|
|
registerReader(name: string, reader: GetMetricReader) {
|
|
|
|
this.readers.register(name, reader);
|
|
|
|
}
|
|
|
|
|
|
|
|
getReader(name: string) {
|
|
|
|
return this.readers.get(name);
|
|
|
|
}
|
|
|
|
|
|
|
|
addView(...view: View[]) {
|
|
|
|
this.views.push(...view);
|
|
|
|
}
|
|
|
|
|
|
|
|
getMeter(name?: string, version?: string) {
|
|
|
|
return this.provider.getMeter(name || this.meterName, version || this.version);
|
|
|
|
}
|
|
|
|
|
|
|
|
start() {
|
|
|
|
let readerName = this.readerName;
|
|
|
|
if (typeof readerName === 'string') {
|
|
|
|
readerName = readerName.split(',');
|
|
|
|
}
|
|
|
|
readerName.forEach((name) => {
|
|
|
|
const reader = this.getReader(name)();
|
|
|
|
this.provider.addMetricReader(reader);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
shutdown() {
|
|
|
|
return this.provider.shutdown();
|
|
|
|
}
|
|
|
|
}
|