Skip to content

Commit ece5137

Browse files
committed
feat: add loadContext method to fix pino trace linking issue
1 parent ef92fa6 commit ece5137

File tree

1 file changed

+59
-11
lines changed
  • packages/node-opentelemetry/src/otel-logger

1 file changed

+59
-11
lines changed

packages/node-opentelemetry/src/otel-logger/index.ts

Lines changed: 59 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
1-
import { Attributes, diag } from '@opentelemetry/api';
2-
import { Logger as OtelLogger, logs } from '@opentelemetry/api-logs';
1+
import {
2+
Attributes,
3+
context as apiContext,
4+
diag,
5+
trace,
6+
} from '@opentelemetry/api';
7+
import { Logger as OtelLogger, LogRecord, logs } from '@opentelemetry/api-logs';
38
import { getStringFromEnv } from '@opentelemetry/core';
49
import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http';
510
import {
@@ -29,6 +34,47 @@ import {
2934

3035
const LOG_PREFIX = `⚠️ [LOGGER]`;
3136

37+
/**
38+
* Load context from attributes and set it to logRecord.context
39+
*
40+
* @param {LogRecord} logRecord
41+
* @returns {LogRecord}
42+
*/
43+
function loadContext(logRecord: LogRecord): LogRecord {
44+
let context = apiContext.active();
45+
let attributes = logRecord.attributes;
46+
47+
if (typeof attributes !== 'undefined') {
48+
const { trace_id, span_id, trace_flags, ...otherAttributes } =
49+
logRecord.attributes as Attributes & {
50+
trace_id?: string;
51+
span_id?: string;
52+
trace_flags?: number;
53+
};
54+
55+
if (
56+
typeof trace_id !== 'undefined' &&
57+
typeof span_id !== 'undefined' &&
58+
typeof trace_flags !== 'undefined'
59+
) {
60+
context = trace.setSpanContext(context, {
61+
traceId: trace_id,
62+
spanId: span_id,
63+
traceFlags: trace_flags,
64+
isRemote: true,
65+
});
66+
}
67+
68+
attributes = otherAttributes;
69+
}
70+
71+
return {
72+
...logRecord,
73+
attributes,
74+
context,
75+
};
76+
}
77+
3278
export type LoggerOptions = {
3379
baseUrl?: string;
3480
bufferSize?: number;
@@ -156,14 +202,16 @@ export class Logger {
156202
}
157203

158204
postMessage(level: string, body: string, attributes: Attributes = {}): void {
159-
this.logger.emit({
160-
// TODO: should map to otel severity number
161-
severityNumber: 0,
162-
// TODO: set up the mapping between different downstream log levels
163-
severityText: level,
164-
body,
165-
attributes,
166-
timestamp: this.parseTimestamp(attributes),
167-
});
205+
this.logger.emit(
206+
loadContext({
207+
// TODO: should map to otel severity number
208+
severityNumber: 0,
209+
// TODO: set up the mapping between different downstream log levels
210+
severityText: level,
211+
body,
212+
attributes,
213+
timestamp: this.parseTimestamp(attributes),
214+
}),
215+
);
168216
}
169217
}

0 commit comments

Comments
 (0)