@autotelic/fastify-opentelemetry

中文文档
0.23.0发布于 2025/11/10MITTypeScriptCommonJS近 30 天下载 5.7万

A Fastify plugin for OpenTelemetry

原始使用文档
文档目录7 节
  1. Usage
  2. Examples
  3. API
  4. Configuration
  5. Request Decorator
  6. Hooks
  7. OpenTelemetry Compatibility

Fastify OpenTelemetry

A Fastify plugin that uses the OpenTelemetry API to provide request tracing.

Usage

npm i @autotelic/fastify-opentelemetry

Examples

Plugin Usage

// index.js
// Load your OpenTelemetry/API configuration first. Now the configured SDK will be available
// to fastify-opentelemetry. (See the example configuration below.)
require('./openTelemetryConfig')
const openTelemetryPlugin = require('@autotelic/fastify-opentelemetry')
const fastify = require('fastify')();

(async () => {
  await fastify.register(openTelemetryPlugin, { wrapRoutes: true })

  fastify.get('/', async function (request, reply) {
    const {
      activeSpan,
      tracer,
      // context,
      // extract,
      // inject,
    } = request.openTelemetry()
    // Spans started in a wrapped route will automatically be children of the activeSpan.
    const childSpan = tracer.startSpan(`${activeSpan.name} - child process`)
    // doSomeWork()
    childSpan.end()
    return 'OK'
  })

  fastify.listen(3000, (err, address) => {
    if (err) {
      fastify.log.error(err)
      process.exit(1)
    }
  })
})()

OpenTelemetry API Configuration

// openTelemetryConfig.js
const {
  BatchSpanProcessor,
  ConsoleSpanExporter,
  TraceIdRatioBasedSampler
} = require('@opentelemetry/sdk-trace-base')

const { NodeTracerProvider } = require('@opentelemetry/sdk-trace-node')

// Configure a tracer provider.
const provider = new NodeTracerProvider({
  sampler: new TraceIdRatioBasedSampler(0.5)
})

// Add a span exporter.
provider.addSpanProcessor(
  new BatchSpanProcessor(new ConsoleSpanExporter())
)

// Register a global tracer provider.
provider.register()

// Note: the above is just a basic example. fastify-opentelemetry is compatible with any
// @opentelemetry/api configuration.

See /example for a working example app. To run the example app locally, first clone this repo and then npm i and run:

npm run dev

API

Configuration

This plugin leaves all tracer configuration to the OpenTelemetry API. The tracer and propagation method are pulled in from the global tracer provider and global propagator, respectively. This allows the config for the plugin itself to be minimal.

The plugin accepts the the following configuration properties:

  • exposeApi : boolean - Used to prevent the plugin from decorating the request. By default the request will be decorated (i.e. defaults to true).

  • formatSpanName : (FastifyRequest) => string - Custom formatter for the span name. The default format is `${req.method} ${req.routeOptions.url}`.

  • formatSpanAttributes : object - Contains formatting functions for span attributes. Properties:

    • request: (FastifyRequest) => object - On request, the returned object will be added to the current span's attributes. The default request attributes are:

      { 'req.method': request.raw.method, 'req.url': request.raw.url }
      
    • reply: (FastifyReply) => object - On reply, the returned object will be added to the current span's attributes. The default reply attributes are:

      { 'reply.statusCode': reply.statusCode }
      
    • error: (Error) => object - On error, the returned object will be added to the current span's attributes. The default error attributes are:

      {
        'error.name': error.name,
        'error.message': error.message,
        'error.stack': error.stack
      }
      
  • wrapRoutes : boolean | string[] - When true, all route handlers will be executed with an active context equal to request.openTelemetry().context. Also accepts an array containing all route paths that should be wrapped. Optional - disabled by default.

    • Route paths must have a leading / and no trailing / (eg. '/my/exact/route/path').
    • Wrapping a route allows for any span created within the scope of the route handler to automatically become children of the current request's activeSpan. This includes spans created by automated OpenTelemetry instrumentations.
    • A global context manager (eg. AsyncHooksContextManager) is required to provide an active context to the route handler.
  • ignoreRoutes : string[] | (path: string, method: string) => boolean - Configure the hooks added by this plugin to ignore certain route paths (ie. no automated tracing for that route). Takes precedence over wrapRoutes.

    • Can be an array of Route paths (following the same format as wrapRoutes).

    • Can be a function that receives a route's path and method, and returns a boolean (return true to ignore). For example, to disable tracing on OPTIONS routes:

      fastify.register(openTelemetryPlugin, {
        ignoreRoutes: (path, method) => method === 'OPTIONS'
      })
      
    • The ignored routes will still have access to request.openTelemetry, but activeSpan will be undefined.

  • propagateToReply : boolean - When true, the current span context will be injected into the reply headers using your registered propagators. Defaults to false.

  • spanOptions : SpanOptions | (FastifyRequest) => SpanOptions - SpanOptions or a function that returns SpanOptions. These will be passed into tracer.startSpan on each request. Defaults to { kind: 1 }.

Request Decorator

This plugin decorates the request with an openTelemetry function that returns an object with the following properties:

  • context: Context - Context containing the active span along with any extracted context.

  • activeSpan: Span - The active span (while this is available via context, here we just provide a shortcut to it.).

  • extract: Propagation.extract - Wraps the propagation API's extract method, and passes in the current request's context as the context argument. This returns a new context and will not affect the request's trace context. Accepts the following arguments:

    • carrier: object - Object containing the context to be extracted.
    • getter: TextMapGetter - Object containing get and keys methods. Used to extract values from carrier. Defaults to OpenTelemetry's defaultTextMapGetter.
  • inject: Propagation.inject - Wraps the propagation API's inject method, and passes in the current request's context as the context argument. Accepts the following arguments:

    • carrier: object - Object the context will be injected into.
    • setter: TextMapSetter - Object containing set method. Used to inject values into the carrier. Defaults to OpenTelemetry's defaultTextMapSetter.
  • tracer: Tracer - The tracer created and used by the plugin.

Hooks

This plugin registers the following Fastify hooks:

  • onRequest: Start the span.

  • onReply: Stop the span.

  • onError: Add error info to span attributes.

  • onRoute: Added only if wrapRoutes is enabled.

  • onSend: Added only if propagateToReply is enabled.

OpenTelemetry Compatibility

As the OpenTelemetry API uses a variable on the global object to store the global API, care needs to be taken to ensure all modules are compatible.

Each version of the OpenTelemetry API will require a specific release of fastify-opentelemetry.

OpenTelemetry API VersionMinimum Fastify OpenTelemetry Version
@opentelemetry/[email protected]@autotelic/[email protected]
@opentelemetry/[email protected]@autotelic/[email protected]
@opentelemetry/[email protected]@autotelic/[email protected]
@opentelemetry/[email protected]@autotelic/[email protected]
@opentelemetry/[email protected]@autotelic/[email protected]
@opentelemetry/[email protected]@autotelic/[email protected]
@opentelemetry/[email protected]@autotelic/[email protected]
@opentelemetry/[email protected]@autotelic/[email protected]
@opentelemetry/[email protected]@autotelic/[email protected]
@opentelemetry/[email protected]@autotelic/[email protected]
@opentelemetry/[email protected]@autotelic/[email protected]

版本与发布记录

@autotelic/fastify-opentelemetry 共发布 32 个版本,首次发布于 2020/07/03;过去 12 个月发布了 1 个版本。

版本发布日期距今
0.23.0latest2025/11/1011 个月前
0.22.12025/01/291.8 年前
0.22.02024/09/212 年前
0.21.02024/04/102 年前
0.20.02024/03/062 年前
0.19.02024/02/072 年前

关于 @autotelic/fastify-opentelemetry 的常见问题

@autotelic/fastify-opentelemetry 是什么?

A Fastify plugin for OpenTelemetry

如何安装 @autotelic/fastify-opentelemetry?

在项目目录运行 npm install @autotelic/fastify-opentelemetry,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@opentelemetry/api(^1.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@autotelic/fastify-opentelemetry 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@autotelic/fastify-opentelemetry 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@autotelic/fastify-opentelemetry 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@autotelic/fastify-opentelemetry 可以商用吗?

@autotelic/fastify-opentelemetry 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@autotelic/fastify-opentelemetry 的下载量有多少?

根据 npm 官方下载统计,@autotelic/fastify-opentelemetry 在 2026/10/07 – 2026/11/05 这 30 天内被下载 57,444 次,日均约 1,915 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@autotelic/fastify-opentelemetry 还在维护吗?

最新版本 0.23.0 发布于 2025/11/10(11 个月前);至今共发布 32 个版本,其中过去 12 个月发布了 1 个;首次发布于 2020/07/03。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。