{"version":3,"file":"log-sending-utils.cjs","names":["SeverityNumber","Writable","logs","PACKAGE_NAME","PACKAGE_VERSION","ATTR_OTEL_EVENT_NAME","millisToHrTime"],"sources":["../src/log-sending-utils.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport { Writable } from 'stream';\n\nimport { logs, Logger, SeverityNumber } from '@opentelemetry/api';\n/** @knipignore */\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\nimport { millisToHrTime } from '@opentelemetry/core';\nimport { ATTR_OTEL_EVENT_NAME } from '@opentelemetry/semantic-conventions';\n\n// This block is a copy (modulo code style and TypeScript types) of the Pino\n// code that defines log level value and names. This file is part of\n// *instrumenting* Pino, so we want to avoid a dependency on the library.\nconst DEFAULT_LEVELS = {\n  trace: 10,\n  debug: 20,\n  info: 30,\n  warn: 40,\n  error: 50,\n  fatal: 60,\n};\n\nconst OTEL_SEV_NUM_FROM_PINO_LEVEL: { [level: number]: SeverityNumber } = {\n  [DEFAULT_LEVELS.trace]: SeverityNumber.TRACE,\n  [DEFAULT_LEVELS.debug]: SeverityNumber.DEBUG,\n  [DEFAULT_LEVELS.info]: SeverityNumber.INFO,\n  [DEFAULT_LEVELS.warn]: SeverityNumber.WARN,\n  [DEFAULT_LEVELS.error]: SeverityNumber.ERROR,\n  [DEFAULT_LEVELS.fatal]: SeverityNumber.FATAL,\n};\n\nconst EXTRA_SEV_NUMS = [\n  SeverityNumber.TRACE2,\n  SeverityNumber.TRACE3,\n  SeverityNumber.TRACE4,\n  SeverityNumber.DEBUG2,\n  SeverityNumber.DEBUG3,\n  SeverityNumber.DEBUG4,\n  SeverityNumber.INFO2,\n  SeverityNumber.INFO3,\n  SeverityNumber.INFO4,\n  SeverityNumber.WARN2,\n  SeverityNumber.WARN3,\n  SeverityNumber.WARN4,\n  SeverityNumber.ERROR2,\n  SeverityNumber.ERROR3,\n  SeverityNumber.ERROR4,\n  SeverityNumber.FATAL2,\n  SeverityNumber.FATAL3,\n  SeverityNumber.FATAL4,\n];\n\nfunction severityNumberFromPinoLevel(lvl: number) {\n  // Fast common case: one of the known levels\n  const sev = OTEL_SEV_NUM_FROM_PINO_LEVEL[lvl];\n  if (sev !== undefined) {\n    return sev;\n  }\n\n  // Otherwise, scale the Pino level range -- 10 (trace) to 70 (fatal+10)\n  // -- onto the extra OTel severity numbers (TRACE2, TRACE3, ..., FATAL4).\n  // Values below trace (10) map to SeverityNumber.TRACE2, which may be\n  // considered a bit weird, but it means the unnumbered levels are always\n  // just for exactly matching values.\n  const relativeLevelWeight = (lvl - 10) / (70 - 10);\n  const otelSevIdx = Math.floor(relativeLevelWeight * EXTRA_SEV_NUMS.length);\n  const cappedOTelIdx = Math.min(\n    EXTRA_SEV_NUMS.length - 1,\n    Math.max(0, otelSevIdx)\n  );\n  const otelSevValue = EXTRA_SEV_NUMS[cappedOTelIdx];\n  return otelSevValue;\n}\n\n/**\n * Return a function that knows how to convert the \"time\" field value on a\n * Pino log record to an OTel LogRecord timestamp value.\n *\n * How to convert the serialized \"time\" on a Pino log record\n * depends on the Logger's `Symbol(pino.time)` prop, configurable\n * via https://getpino.io/#/docs/api?id=timestamp-boolean-function\n *\n * For example:\n *    const logger = pino({timestamp: pino.stdTimeFunctions.isoTime})\n * results in log record entries of the form:\n *    ,\"time\":\"2024-05-17T22:03:25.969Z\"\n * `otelTimestampFromTime` will be given the value of the \"time\" field:\n *   \"2024-05-17T22:03:25.969Z\"\n * which should be parsed to a number of milliseconds since the epoch.\n */\nexport function getTimeConverter(pinoLogger: any, pinoMod: any) {\n  const stdTimeFns = pinoMod.stdTimeFunctions;\n  const loggerTimeFn = pinoLogger[pinoMod.symbols.timeSym];\n  if (loggerTimeFn === stdTimeFns.epochTime) {\n    return (time: number) => time;\n  } else if (loggerTimeFn === stdTimeFns.unixTime) {\n    return (time: number) => time * 1e3;\n  } else if (loggerTimeFn === stdTimeFns.isoTime) {\n    return (time: string) => new Date(time).getTime();\n  } else if (loggerTimeFn === stdTimeFns.nullTime) {\n    return () => Date.now();\n  } else {\n    // The logger has a custom time function. Don't guess.\n    return () => NaN;\n  }\n}\n\ninterface OTelPinoStreamOptions {\n  messageKey: string;\n  errorKey: string;\n  levels: any; // Pino.LevelMapping\n  otelTimestampFromTime: (time: any) => number;\n}\n\n/**\n * A Pino stream for sending records to the OpenTelemetry Logs API.\n *\n * - This stream emits an 'unknown' event on an unprocessable pino record.\n *   The event arguments are: `logLine: string`, `err: string | Error`.\n */\nexport class OTelPinoStream extends Writable {\n  declare private _otelLogger: Logger;\n  declare private _messageKey: string;\n  declare private _errorKey: string;\n  declare private _levels;\n  declare private _otelTimestampFromTime;\n\n  constructor(options: OTelPinoStreamOptions) {\n    super();\n\n    // Note: A PINO_CONFIG event was added to pino (2024-04-04) to send config\n    // to transports. Eventually OTelPinoStream might be able to use this\n    // for auto-configuration in newer pino versions. The event currently does\n    // not include the `timeSym` value that is needed here, however.\n    this._messageKey = options.messageKey;\n    this._errorKey = options.errorKey;\n    this._levels = options.levels;\n    this._otelTimestampFromTime = options.otelTimestampFromTime;\n\n    // Cannot use `instrumentation.logger` until have delegating LoggerProvider:\n    // https://github.com/open-telemetry/opentelemetry-js/issues/4399\n    this._otelLogger = logs.getLogger(PACKAGE_NAME, PACKAGE_VERSION);\n  }\n\n  override _write(s: string, _encoding: string, callback: Function) {\n    /* istanbul ignore if */\n    if (!s) {\n      return;\n    }\n\n    // Parse, and handle edge cases similar to how `pino-abtract-transport` does:\n    // https://github.com/pinojs/pino-abstract-transport/blob/v1.2.0/index.js#L28-L45\n    // - Emitting an 'unknown' event on parse error mimicks pino-abstract-transport.\n    let recObj;\n    try {\n      recObj = JSON.parse(s);\n    } catch (parseErr) {\n      // Invalid JSON suggests a bug in Pino, or a logger configuration bug\n      // (a bogus `options.timestamp` or serializer).\n      this.emit('unknown', s.toString(), parseErr);\n      callback();\n      return;\n    }\n    /* istanbul ignore if */\n    if (recObj === null) {\n      this.emit('unknown', s.toString(), 'Null value ignored');\n      callback();\n      return;\n    }\n    /* istanbul ignore if */\n    if (typeof recObj !== 'object') {\n      recObj = {\n        data: recObj,\n      };\n    }\n\n    const {\n      time,\n      [this._messageKey]: body,\n      [this._errorKey]: exception,\n      level, // eslint-disable-line @typescript-eslint/no-unused-vars\n\n      // The typical Pino `hostname` and `pid` fields are removed because they\n      // are redundant with the OpenTelemetry `host.name` and `process.pid`\n      // Resource attributes, respectively. This code cannot change the\n      // LoggerProvider's `resource`, so getting the OpenTelemetry equivalents\n      // depends on the user using the OpenTelemetry HostDetector and\n      // ProcessDetector.\n      // https://getpino.io/#/docs/api?id=opt-base\n      hostname, // eslint-disable-line @typescript-eslint/no-unused-vars\n      pid, // eslint-disable-line @typescript-eslint/no-unused-vars\n\n      // The `trace_id` et al fields that may have been added by the\n      // \"log correlation\" feature are stripped, because they are redundant.\n      trace_id, // eslint-disable-line @typescript-eslint/no-unused-vars\n      span_id, // eslint-disable-line @typescript-eslint/no-unused-vars\n      trace_flags, // eslint-disable-line @typescript-eslint/no-unused-vars\n\n      [ATTR_OTEL_EVENT_NAME]: eventName,\n\n      ...attributes\n    } = recObj;\n\n    let timestamp = this._otelTimestampFromTime(time);\n    if (isNaN(timestamp)) {\n      attributes['time'] = time; // save the unexpected \"time\" field to attributes\n      timestamp = Date.now();\n    }\n\n    // This avoids a possible subtle bug when a Pino logger uses\n    // `time: pino.stdTimeFunctions.unixTime` and logs in the first half-second\n    // since process start. The rounding involved results in:\n    //    timestamp < performance.timeOrigin\n    // If that is passed to Logger.emit() it will be misinterpreted by\n    // `timeInputToHrTime` as a `performance.now()` value.\n    const timestampHrTime = millisToHrTime(timestamp);\n\n    // Prefer using `stream.lastLevel`, because `recObj.level` can be customized\n    // to anything via `formatters.level`\n    // (https://getpino.io/#/docs/api?id=formatters-object).\n    const lastLevel = (this as any).lastLevel;\n\n    const normalizedEventName =\n      typeof eventName === 'string' ? eventName : undefined;\n\n    const otelRec = {\n      timestamp: timestampHrTime,\n      observedTimestamp: timestampHrTime,\n      severityNumber: severityNumberFromPinoLevel(lastLevel),\n      severityText: this._levels.labels[lastLevel],\n      body,\n      attributes,\n      exception: normalizeException(exception),\n      ...(normalizedEventName !== undefined\n        ? { eventName: normalizedEventName }\n        : {}),\n    };\n\n    this._otelLogger.emit(otelRec);\n    callback();\n  }\n}\n\nfunction normalizeException(exception: unknown): unknown {\n  if (!exception || typeof exception !== 'object' || Array.isArray(exception)) {\n    return exception;\n  }\n\n  const exceptionObject = exception as Record<string, unknown>;\n  if (\n    typeof exceptionObject['type'] === 'string' &&\n    typeof exceptionObject['name'] !== 'string'\n  ) {\n    exceptionObject['name'] = exceptionObject['type'];\n  }\n\n  return exceptionObject;\n}\n"],"mappings":";;;;;;;AAgBA,MAAM,iBAAiB;CACrB,OAAO;CACP,OAAO;CACP,MAAM;CACN,MAAM;CACN,OAAO;CACP,OAAO;AACT;AAEA,MAAM,+BAAoE;EACvE,eAAe,QAAQA,mBAAAA,eAAe;EACtC,eAAe,QAAQA,mBAAAA,eAAe;EACtC,eAAe,OAAOA,mBAAAA,eAAe;EACrC,eAAe,OAAOA,mBAAAA,eAAe;EACrC,eAAe,QAAQA,mBAAAA,eAAe;EACtC,eAAe,QAAQA,mBAAAA,eAAe;AACzC;AAEA,MAAM,iBAAiB;CACrBA,mBAAAA,eAAe;CACfA,mBAAAA,eAAe;CACfA,mBAAAA,eAAe;CACfA,mBAAAA,eAAe;CACfA,mBAAAA,eAAe;CACfA,mBAAAA,eAAe;CACfA,mBAAAA,eAAe;CACfA,mBAAAA,eAAe;CACfA,mBAAAA,eAAe;CACfA,mBAAAA,eAAe;CACfA,mBAAAA,eAAe;CACfA,mBAAAA,eAAe;CACfA,mBAAAA,eAAe;CACfA,mBAAAA,eAAe;CACfA,mBAAAA,eAAe;CACfA,mBAAAA,eAAe;CACfA,mBAAAA,eAAe;CACfA,mBAAAA,eAAe;AACjB;AAEA,SAAS,4BAA4B,KAAa;CAEhD,MAAM,MAAM,6BAA6B;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