UNPKG

@cerbos/opentelemetry

Version:

OpenTelemetry instrumentation for the @cerbos/grpc and @cerbos/http client libraries

94 lines 2.75 kB
import { diag, metrics, trace } from "@opentelemetry/api"; import { addInstrumenter, removeInstrumenter } from "@cerbos/core/~internal"; import { Instruments } from "./instruments.js"; import { name, version } from "./metadata.js"; import { Transport } from "./transport.js"; /** * OpenTelemetry instrumentation for Cerbos clients. * * @example * ```typescript * import { CerbosInstrumentation } from "@cerbos/opentelemetry"; * import { registerInstrumentations } from "@opentelemetry/instrumentation"; * * registerInstrumentations({ * instrumentations: [...yourOtherInstrumentations, new CerbosInstrumentation()], * }); * ``` * * @public */ export class CerbosInstrumentation { /** * Name of the instrumentation. */ instrumentationName = name; /** * Version of the instrumentation. */ instrumentationVersion = version; /** @internal */ ["~tracer"]; diag; instrumenter; config; instruments; constructor(config = {}) { this.diag = diag.createComponentLogger({ namespace: name, }); this.config = { enabled: true, ...config }; this["~tracer"] = trace.getTracer(name, version); this.instrumenter = (transport) => new Transport(this, transport); if (this.config.enabled) { this.enable(); } } /** * Gets the instrumentation configuration. */ getConfig() { return this.config; } /** * Sets the instrumentation configuration. * * @remarks * Changing `enabled` via this method has no effect. * Use the {@link CerbosInstrumentation.disable} and {@link CerbosInstrumentation.enable} methods instead. */ setConfig(config) { this.config = config; } /** * Override the meter provider, which otherwise defaults to the global meter provider. */ setMeterProvider(meterProvider) { this.instruments = new Instruments(meterProvider); } /** * Override the tracer provider, which otherwise defaults to the global tracer provider. */ setTracerProvider(tracerProvider) { this["~tracer"] = tracerProvider.getTracer(name, version); } /** * Enables the instrumentation. */ enable() { this.diag.debug("Enabling Cerbos client instrumentation"); addInstrumenter(this.instrumenter); } /** * Disables the instrumentation. */ disable() { this.diag.debug("Disabling Cerbos client instrumentation"); removeInstrumenter(this.instrumenter); } /** @internal */ get ["~instruments"]() { return (this.instruments ??= new Instruments(metrics)); } } //# sourceMappingURL=instrumentation.js.map