|
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'; |
3 | 8 | import { getStringFromEnv } from '@opentelemetry/core'; |
4 | 9 | import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-http'; |
5 | 10 | import { |
@@ -29,6 +34,47 @@ import { |
29 | 34 |
|
30 | 35 | const LOG_PREFIX = `⚠️ [LOGGER]`; |
31 | 36 |
|
| 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 | + |
32 | 78 | export type LoggerOptions = { |
33 | 79 | baseUrl?: string; |
34 | 80 | bufferSize?: number; |
@@ -156,14 +202,16 @@ export class Logger { |
156 | 202 | } |
157 | 203 |
|
158 | 204 | 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 | + ); |
168 | 216 | } |
169 | 217 | } |
0 commit comments