{"version":3,"file":"instrumentation.cjs","names":["InstrumentationBase","PACKAGE_NAME","PACKAGE_VERSION","InstrumentationNodeModuleDefinition","getTimeConverter","OTelPinoStream","trace","context","isSpanContextValid"],"sources":["../src/instrumentation.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n  context,\n  diag,\n  trace,\n  isSpanContextValid,\n  Span,\n} from '@opentelemetry/api';\nimport {\n  InstrumentationBase,\n  InstrumentationNodeModuleDefinition,\n  safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport { PinoInstrumentationConfig } from './types';\n/** @knipignore */\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\nimport { getTimeConverter, OTelPinoStream } from './log-sending-utils';\n\nconst pinoVersions = ['>=5.14.0 <11'];\n\nconst DEFAULT_LOG_KEYS = {\n  traceId: 'trace_id',\n  spanId: 'span_id',\n  traceFlags: 'trace_flags',\n};\n\nexport class PinoInstrumentation extends InstrumentationBase<PinoInstrumentationConfig> {\n  constructor(config: PinoInstrumentationConfig = {}) {\n    super(PACKAGE_NAME, PACKAGE_VERSION, config);\n  }\n\n  protected init() {\n    return [\n      new InstrumentationNodeModuleDefinition('pino', pinoVersions, module => {\n        const isESM = module[Symbol.toStringTag] === 'Module';\n        const moduleExports = isESM ? module.default : module;\n        const instrumentation = this;\n\n        const patchedPino = Object.assign((...args: unknown[]) => {\n          const config = instrumentation.getConfig();\n          const isEnabled = instrumentation.isEnabled();\n\n          const logger = moduleExports(...args);\n\n          // Setup \"log correlation\" -- injection of `trace_id` et al fields.\n          // Note: If the Pino logger is configured with `nestedKey`, then\n          // the `trace_id` et al fields added by `otelMixin` will be nested\n          // as well. https://getpino.io/#/docs/api?id=mixin-function\n          const otelMixin = instrumentation._getMixinFunction();\n          const mixinSym = moduleExports.symbols.mixinSym;\n          const origMixin = logger[mixinSym];\n          if (origMixin === undefined) {\n            logger[mixinSym] = otelMixin;\n          } else {\n            logger[mixinSym] = (\n              ctx: object,\n              level: number,\n              ...rest: unknown[]\n            ) => {\n              return Object.assign(\n                otelMixin(ctx, level),\n                origMixin(ctx, level, ...rest)\n              );\n            };\n          }\n\n          // Setup \"log sending\" -- sending log records to the Logs API.\n          // This depends on `pino.multistream`, which was added in v7.0.0.\n          if (\n            isEnabled &&\n            !config.disableLogSending &&\n            typeof moduleExports.multistream === 'function'\n          ) {\n            const otelTimestampFromTime = getTimeConverter(\n              logger,\n              moduleExports\n            );\n            const otelStream = new OTelPinoStream({\n              messageKey: logger[moduleExports.symbols.messageKeySym],\n              errorKey: logger[moduleExports.symbols.errorKeySym],\n              levels: logger.levels,\n              otelTimestampFromTime,\n            });\n            (otelStream as any)[Symbol.for('pino.metadata')] = true; // for `stream.lastLevel`\n\n            // An error typically indicates a Pino bug, or logger configuration\n            // bug. `diag.warn` *once* for the first error on the assumption\n            // subsequent ones stem from the same bug.\n            otelStream.once('unknown', (line, err) => {\n              instrumentation._diag.warn(\n                'could not send pino log line (will only log first occurrence)',\n                { line, err }\n              );\n            });\n\n            // Use pino's own `multistream` to send to the original stream and\n            // to the OTel Logs API/SDK.\n            // https://getpino.io/#/docs/api?id=pinomultistreamstreamsarray-opts-gt-multistreamres\n            const origStream = logger[moduleExports.symbols.streamSym];\n            logger[moduleExports.symbols.streamSym] = moduleExports.multistream(\n              [\n                // Use level `0` to never not log a record given to the stream.\n                { level: 0, stream: origStream },\n                { level: 0, stream: otelStream },\n              ],\n              { levels: logger.levels.values }\n            );\n          }\n\n          return logger;\n        }, moduleExports);\n\n        if (typeof patchedPino.pino === 'function') {\n          patchedPino.pino = patchedPino;\n        }\n        if (typeof patchedPino.default === 'function') {\n          patchedPino.default = patchedPino;\n        }\n        /* istanbul ignore if */\n        if (isESM) {\n          if (module.pino) {\n            // This was added in pino@6.8.0 (https://github.com/pinojs/pino/pull/936).\n            module.pino = patchedPino;\n          }\n          module.default = patchedPino;\n        }\n\n        return patchedPino;\n      }),\n    ];\n  }\n\n  private _callHook(span: Span, record: Record<string, string>, level: number) {\n    const { logHook } = this.getConfig();\n\n    if (!logHook) {\n      return;\n    }\n\n    safeExecuteInTheMiddle(\n      () => logHook(span, record, level),\n      err => {\n        if (err) {\n          diag.error('pino instrumentation: error calling logHook', err);\n        }\n      },\n      true\n    );\n  }\n\n  private _getMixinFunction() {\n    const instrumentation = this;\n    return function otelMixin(_context: object, level: number) {\n      if (\n        !instrumentation.isEnabled() ||\n        instrumentation.getConfig().disableLogCorrelation\n      ) {\n        return {};\n      }\n\n      const span = trace.getSpan(context.active());\n\n      if (!span) {\n        return {};\n      }\n\n      const spanContext = span.spanContext();\n\n      if (!isSpanContextValid(spanContext)) {\n        return {};\n      }\n\n      const logKeys = instrumentation.getConfig().logKeys ?? DEFAULT_LOG_KEYS;\n\n      const record = {\n        [logKeys.traceId]: spanContext.traceId,\n        [logKeys.spanId]: spanContext.spanId,\n        [logKeys.traceFlags]: `0${spanContext.traceFlags.toString(16)}`,\n      };\n\n      instrumentation._callHook(span, record, level);\n\n      return record;\n    };\n  }\n}\n"],"mappings":";;;;;;AAsBA,MAAM,eAAe,CAAC,cAAc;AAEpC,MAAM,mBAAmB;CACvB,SAAS;CACT,QAAQ;CACR,YAAY;AACd;AAEA,IAAa,sBAAb,cAAyCA,+BAAAA,oBAA+C;CACtF,YAAY,SAAoC,CAAC,GAAG;EAClD,MAAMC,gBAAAA,cAAcC,gBAAAA,iBAAiB,MAAM;CAC7C;CAEA,OAAiB;EACf,OAAO,CACL,IAAIC,+BAAAA,oCAAoC,QAAQ,eAAc,WAAU;GACtE,MAAM,QAAQ,OAAO,OAAO,iBAAiB;GAC7C,MAAM,gBAAgB,QAAQ,OAAO,UAAU;GAC/C,MAAM,kBAAkB;GAExB,MAAM,cAAc,OAAO,QAAQ,GAAG,SAAoB;IACxD,MAAM,SAAS,gBAAgB,UAAU;IACzC,MAAM,YAAY,gBAAgB,UAAU;IAE5C,MAAM,SAAS,cAAc,GAAG,IAAI;IAMpC,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