Telemetry 遥测

注意

该功能目前为实验性功能。

NocoBase 的遥测(Telemetry)模块基于 OpenTelemetry 封装,用于收集链路(Trace)和监控指标(Metric)数据,增强 NocoBase 的可观测性(Observability)。

插桩

指标

const meter = app.telemetry.metric.getMeter();
const counter = meter.createCounter('event_counter', {});
counter.add(1);

详细用法见 OpenTelemetry - Acquiring a Meter

链路

const tracer = app.telemetry.trace.getTracer();
tracer.startActiveSpan();
tracer.startSpan();

详细用法见 OpenTelemetry - Acquiring a Tracer

工具库

import { Plugin } from '@nocobase/server';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';

class InstrumentationPlugin extends Plugin {
  afterAdd() {
    this.app.on('beforeLoad', (app) => {
      app.telemetry.addInstrumentation(getNodeAutoInstrumentations());
    });
  }
}
注意

NocoBase 中遥测模块的初始化位置为 app.beforeLoad,因此并不是所有插桩库都适用于 NocoBase。 比如 instrumentation-koa 需要在 Koa 实例化之前引入,而 NocoBase 的 Application 虽然基于 Koa,但遥测模块是在 Application 实例化之后才初始化的,所以无法使用。

详细用法见 OpenTelemetry - Libraries

采集

指标

import { Plugin } from '@nocobase/server';
import {
  PeriodicExportingMetricReader,
  ConsoleMetricExporter,
} from '@opentelemetry/sdk-metrics';

class MetricReaderPlugin extends Plugin {
  afterAdd() {
    this.app.on('beforeLoad', (app) => {
      app.telemetry.metric.registerReader(
        'console',
        () =>
          new PeriodicExportingMetricReader({
            exporter: new ConsoleMetricExporter(),
          }),
      );
    });
  }
}

链路

import { Plugin } from '@nocobase/server';
import {
  BatchSpanProcessor,
  ConsoleSpanExporter,
} from '@opentelemetry/sdk-trace-base';

class TraceSpanProcessorPlugin extends Plugin {
  afterAdd() {
    this.app.on('beforeLoad', (app) => {
      app.telemetry.trace.registerProcessor(
        'console',
        () => new BatchSpanProcessor(new ConsoleSpanExporter()),
      );
    });
  }
}

详细用法见 OpenTelemetry - Exporters

相关链接