@opentelemetry/instrumentation-winston 0.35.0 → 0.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  [![NPM Published Version][npm-img]][npm-url]
4
4
  [![Apache License][license-image]][license-image]
5
5
 
6
- This module provides automatic instrumentation for injection of trace context for the [`winston`](https://www.npmjs.com/package/winston) module, which may be loaded using the [`@opentelemetry/sdk-trace-node`](https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-sdk-trace-node) package and is included in the [`@opentelemetry/auto-instrumentations-node`](https://www.npmjs.com/package/@opentelemetry/auto-instrumentations-node) bundle.
6
+ This module provides automatic instrumentation of the [`winston`](https://www.npmjs.com/package/winston) module to inject trace-context into Winston log records (log correlation) and to send Winston logging to the OpenTelemetry Logging SDK (log sending). It may be loaded using the [`@opentelemetry/sdk-trace-node`](https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-sdk-trace-node) package and is included in the [`@opentelemetry/auto-instrumentations-node`](https://www.npmjs.com/package/@opentelemetry/auto-instrumentations-node) bundle.
7
7
 
8
8
  If total installation size is not constrained, it is recommended to use the [`@opentelemetry/auto-instrumentations-node`](https://www.npmjs.com/package/@opentelemetry/auto-instrumentations-node) bundle with [@opentelemetry/sdk-node](`https://www.npmjs.com/package/@opentelemetry/sdk-node`) for the most seamless instrumentation experience.
9
9
 
@@ -19,47 +19,92 @@ npm install --save @opentelemetry/instrumentation-winston
19
19
 
20
20
  ```js
21
21
  const { NodeTracerProvider } = require('@opentelemetry/sdk-trace-node');
22
+ const logsAPI = require('@opentelemetry/api-logs');
23
+ const {
24
+ LoggerProvider,
25
+ SimpleLogRecordProcessor,
26
+ ConsoleLogRecordExporter,
27
+ } = require('@opentelemetry/sdk-logs');
22
28
  const { WinstonInstrumentation } = require('@opentelemetry/instrumentation-winston');
23
29
  const { registerInstrumentations } = require('@opentelemetry/instrumentation');
24
30
 
25
- const provider = new NodeTracerProvider();
26
- provider.register();
31
+ const tracerProvider = new NodeTracerProvider();
32
+ tracerProvider.register();
33
+
34
+ // To start a logger, you first need to initialize the Logger provider.
35
+ const loggerProvider = new LoggerProvider();
36
+ // Add a processor to export log record
37
+ loggerProvider.addLogRecordProcessor(
38
+ new SimpleLogRecordProcessor(new ConsoleLogRecordExporter())
39
+ );
40
+ logsAPI.logs.setGlobalLoggerProvider(loggerProvider);
27
41
 
28
42
  registerInstrumentations({
29
- instrumentations: [
30
- new WinstonInstrumentation({
31
- // Optional hook to insert additional context to log metadata.
32
- // Called after trace context is injected to metadata.
33
- logHook: (span, record) => {
34
- record['resource.service.name'] = provider.resource.attributes['service.name'];
35
- },
36
- }),
37
- // other instrumentations
38
- ],
43
+ instrumentations: [
44
+ new WinstonInstrumentation({
45
+ // See below for Winston instrumentation options.
46
+ }),
47
+ ],
39
48
  });
40
49
 
41
50
  const winston = require('winston');
42
51
  const logger = winston.createLogger({
43
- transports: [new winston.transports.Console()],
52
+ transports: [new winston.transports.Console()],
44
53
  })
45
54
  logger.info('foobar');
46
55
  // {"message":"foobar","trace_id":"e21c7a95fff34e04f77c7bd518779621","span_id":"b7589a981fde09f4","trace_flags":"01", ...}
47
56
  ```
48
57
 
49
- ### Fields added to Winston metadata
58
+ ### Winston instrumentation options
59
+
60
+ | Option | Type | Description |
61
+ | ----------------------- | ----------------- | ----------- |
62
+ | `disableLogSending` | `boolean` | Whether to disable [log sending](#log-sending). Default `false`. |
63
+ | `disableLogCorrelation` | `boolean` | Whether to disable [log correlation](#log-correlation). Default `false`. |
64
+ | `logHook` | `LogHookFunction` | An option hook to inject additional context to a log record after trace-context has been added. This requires `disableLogCorrelation` to be false. |
65
+
66
+ ### Log sending
67
+
68
+ Winston Logger will automatically send log records to the OpenTelemetry Logs SDK if not explicitly disabled in config and @opentelemetry/winston-transport npm package is installed in the project. The OpenTelemetry SDK can be configured to handle those records, for example, sending them on to an OpenTelemetry collector for log archiving and processing. The example above shows a minimal configuration that emits OpenTelemetry log records to the console for debugging.
69
+
70
+ If the OpenTelemetry SDK is not configured with a Logger provider, then this will be a no-op.
71
+
72
+ Log sending can be disabled with the `disableLogSending: true` option. Log sending is only available for Winston version 3 and later.
73
+
74
+ ```bash
75
+ npm install --save @opentelemetry/winston-transport
76
+ ```
77
+
78
+ ### Log correlation
50
79
 
51
- For the current active span, the following fields are injected:
80
+ Winston logger calls in the context of a tracing span will have fields
81
+ indentifying the span added to the log record. This allows
82
+ [correlating](https://opentelemetry.io/docs/specs/otel/logs/#log-correlation)
83
+ log records with tracing data. The added fields are
84
+ ([spec](https://opentelemetry.io/docs/specs/otel/compatibility/logging_trace_context/)):
52
85
 
53
86
  * `trace_id`
54
87
  * `span_id`
55
88
  * `trace_flags`
56
89
 
57
- When no span context is active or the span context is invalid, injection is skipped.
90
+ After adding these fields, the optional `logHook` is called to allow injecting additional fields. For example:
91
+
92
+ ```js
93
+ logHook: (span, record) => {
94
+ record['resource.service.name'] = provider.resource.attributes['service.name'];
95
+ }
96
+ ```
97
+
98
+ Log injection can be disabled with the `disableLogCorrelation: true` option.
58
99
 
59
100
  ### Supported versions
60
101
 
61
102
  `1.x`, `2.x`, `3.x`
62
103
 
104
+ Log sending
105
+
106
+ `3.x`
107
+
63
108
  ## Useful links
64
109
 
65
110
  * For more information on OpenTelemetry, visit: <https://opentelemetry.io/>
@@ -8,5 +8,7 @@ export declare class WinstonInstrumentation extends InstrumentationBase {
8
8
  private _callHook;
9
9
  private _getPatchedWrite;
10
10
  private _getPatchedLog;
11
+ private _getPatchedConfigure;
12
+ private _handleLogCorrelation;
11
13
  }
12
14
  //# sourceMappingURL=instrumentation.d.ts.map
@@ -26,38 +26,46 @@ class WinstonInstrumentation extends instrumentation_1.InstrumentationBase {
26
26
  super('@opentelemetry/instrumentation-winston', version_1.VERSION, config);
27
27
  }
28
28
  init() {
29
- return [
30
- new instrumentation_1.InstrumentationNodeModuleDefinition('winston', winston3Versions, moduleExports => moduleExports, () => { }, [
31
- new instrumentation_1.InstrumentationNodeModuleFile('winston/lib/winston/logger.js', winston3Versions, (logger, moduleVersion) => {
32
- this._diag.debug(`Applying patch for winston@${moduleVersion}`);
33
- if ((0, instrumentation_1.isWrapped)(logger.prototype['write'])) {
34
- this._unwrap(logger.prototype, 'write');
35
- }
36
- this._wrap(logger.prototype, 'write', this._getPatchedWrite());
37
- return logger;
38
- }, (logger, moduleVersion) => {
39
- if (logger === undefined)
40
- return;
41
- this._diag.debug(`Removing patch for winston@${moduleVersion}`);
29
+ const winstons3instrumentationNodeModuleDefinition = new instrumentation_1.InstrumentationNodeModuleDefinition('winston', winston3Versions, moduleExports => moduleExports, () => { }, [
30
+ new instrumentation_1.InstrumentationNodeModuleFile('winston/lib/winston/logger.js', winston3Versions, (logger, moduleVersion) => {
31
+ this._diag.debug(`Applying patch for winston@${moduleVersion}`);
32
+ if ((0, instrumentation_1.isWrapped)(logger.prototype['write'])) {
42
33
  this._unwrap(logger.prototype, 'write');
43
- }),
44
- ]),
45
- new instrumentation_1.InstrumentationNodeModuleDefinition('winston', winstonPre3Versions, moduleExports => moduleExports, () => { }, [
46
- new instrumentation_1.InstrumentationNodeModuleFile('winston/lib/winston/logger.js', winstonPre3Versions, (fileExports, moduleVersion) => {
47
- this._diag.debug(`Applying patch for winston@${moduleVersion}`);
48
- const proto = fileExports.Logger.prototype;
49
- if ((0, instrumentation_1.isWrapped)(proto.log)) {
50
- this._unwrap(proto, 'log');
51
- }
52
- this._wrap(proto, 'log', this._getPatchedLog());
53
- return fileExports;
54
- }, (fileExports, moduleVersion) => {
55
- if (fileExports === undefined)
56
- return;
57
- this._diag.debug(`Removing patch for winston@${moduleVersion}`);
58
- this._unwrap(fileExports.Logger.prototype, 'log');
59
- }),
60
- ]),
34
+ }
35
+ this._wrap(logger.prototype, 'write', this._getPatchedWrite());
36
+ // Wrap configure
37
+ if ((0, instrumentation_1.isWrapped)(logger.prototype['configure'])) {
38
+ this._unwrap(logger.prototype, 'configure');
39
+ }
40
+ this._wrap(logger.prototype, 'configure', this._getPatchedConfigure());
41
+ return logger;
42
+ }, (logger, moduleVersion) => {
43
+ if (logger === undefined)
44
+ return;
45
+ this._diag.debug(`Removing patch for winston@${moduleVersion}`);
46
+ this._unwrap(logger.prototype, 'write');
47
+ this._unwrap(logger.prototype, 'configure');
48
+ }),
49
+ ]);
50
+ const winstons2instrumentationNodeModuleDefinition = new instrumentation_1.InstrumentationNodeModuleDefinition('winston', winstonPre3Versions, moduleExports => moduleExports, () => { }, [
51
+ new instrumentation_1.InstrumentationNodeModuleFile('winston/lib/winston/logger.js', winstonPre3Versions, (fileExports, moduleVersion) => {
52
+ this._diag.debug(`Applying patch for winston@${moduleVersion}`);
53
+ const proto = fileExports.Logger.prototype;
54
+ if ((0, instrumentation_1.isWrapped)(proto.log)) {
55
+ this._unwrap(proto, 'log');
56
+ }
57
+ this._wrap(proto, 'log', this._getPatchedLog());
58
+ return fileExports;
59
+ }, (fileExports, moduleVersion) => {
60
+ if (fileExports === undefined)
61
+ return;
62
+ this._diag.debug(`Removing patch for winston@${moduleVersion}`);
63
+ this._unwrap(fileExports.Logger.prototype, 'log');
64
+ }),
65
+ ]);
66
+ return [
67
+ winstons3instrumentationNodeModuleDefinition,
68
+ winstons2instrumentationNodeModuleDefinition,
61
69
  ];
62
70
  }
63
71
  getConfig() {
@@ -81,17 +89,8 @@ class WinstonInstrumentation extends instrumentation_1.InstrumentationBase {
81
89
  return (original) => {
82
90
  const instrumentation = this;
83
91
  return function patchedWrite(...args) {
84
- const span = api_1.trace.getSpan(api_1.context.active());
85
- if (!span) {
86
- return original.apply(this, args);
87
- }
88
- const spanContext = span.spanContext();
89
- if (!(0, api_1.isSpanContextValid)(spanContext)) {
90
- return original.apply(this, args);
91
- }
92
92
  const record = args[0];
93
- injectRecord(spanContext, record);
94
- instrumentation._callHook(span, record);
93
+ instrumentation._handleLogCorrelation(record);
95
94
  return original.apply(this, args);
96
95
  };
97
96
  };
@@ -100,43 +99,76 @@ class WinstonInstrumentation extends instrumentation_1.InstrumentationBase {
100
99
  return (original) => {
101
100
  const instrumentation = this;
102
101
  return function patchedLog(...args) {
103
- const span = api_1.trace.getSpan(api_1.context.active());
104
- if (!span) {
105
- return original.apply(this, args);
106
- }
107
- const spanContext = span.spanContext();
108
- if (!(0, api_1.isSpanContextValid)(spanContext)) {
109
- return original.apply(this, args);
110
- }
102
+ const record = {};
103
+ instrumentation._handleLogCorrelation(record);
104
+ // Inject in metadata argument
105
+ let isDataInjected = false;
111
106
  for (let i = args.length - 1; i >= 0; i--) {
112
107
  if (typeof args[i] === 'object') {
113
- const record = args[i];
114
- injectRecord(spanContext, record);
115
- instrumentation._callHook(span, record);
116
- return original.apply(this, args);
108
+ args[i] = Object.assign(args[i], record);
109
+ isDataInjected = true;
110
+ break;
117
111
  }
118
112
  }
119
- const record = injectRecord(spanContext);
120
- const insertAt = typeof args[args.length - 1] === 'function'
121
- ? args.length - 1
122
- : args.length;
123
- args.splice(insertAt, 0, record);
124
- instrumentation._callHook(span, record);
113
+ if (!isDataInjected) {
114
+ const insertAt = typeof args[args.length - 1] === 'function'
115
+ ? args.length - 1
116
+ : args.length;
117
+ args.splice(insertAt, 0, record);
118
+ }
125
119
  return original.apply(this, args);
126
120
  };
127
121
  };
128
122
  }
129
- }
130
- exports.WinstonInstrumentation = WinstonInstrumentation;
131
- function injectRecord(spanContext, record) {
132
- const fields = {
133
- trace_id: spanContext.traceId,
134
- span_id: spanContext.spanId,
135
- trace_flags: `0${spanContext.traceFlags.toString(16)}`,
136
- };
137
- if (!record) {
138
- return fields;
123
+ _getPatchedConfigure() {
124
+ return (original) => {
125
+ const instrumentation = this;
126
+ return function patchedConfigure(...args) {
127
+ const config = instrumentation.getConfig();
128
+ if (!config.disableLogSending) {
129
+ if (args && args.length > 0) {
130
+ // Try to load Winston transport
131
+ try {
132
+ const { OpenTelemetryTransportV3, } = require('@opentelemetry/winston-transport');
133
+ const originalTransports = args[0].transports;
134
+ let newTransports = Array.isArray(originalTransports)
135
+ ? originalTransports
136
+ : [];
137
+ const openTelemetryTransport = new OpenTelemetryTransportV3();
138
+ if (originalTransports && !Array.isArray(originalTransports)) {
139
+ newTransports = [originalTransports];
140
+ }
141
+ newTransports.push(openTelemetryTransport);
142
+ args[0].transports = newTransports;
143
+ }
144
+ catch (err) {
145
+ instrumentation._diag.warn('OpenTelemetry Winston transport is not available, log records will not be automatically sent.', err);
146
+ }
147
+ }
148
+ }
149
+ return original.apply(this, args);
150
+ };
151
+ };
152
+ }
153
+ _handleLogCorrelation(record) {
154
+ if (!this.getConfig().disableLogCorrelation) {
155
+ const span = api_1.trace.getSpan(api_1.context.active());
156
+ if (span) {
157
+ const spanContext = span.spanContext();
158
+ if ((0, api_1.isSpanContextValid)(spanContext)) {
159
+ const fields = {
160
+ trace_id: spanContext.traceId,
161
+ span_id: spanContext.spanId,
162
+ trace_flags: `0${spanContext.traceFlags.toString(16)}`,
163
+ };
164
+ const enhancedRecord = Object.assign(record, fields);
165
+ this._callHook(span, enhancedRecord);
166
+ return enhancedRecord;
167
+ }
168
+ }
169
+ }
170
+ return record;
139
171
  }
140
- return Object.assign(record, fields);
141
172
  }
173
+ exports.WinstonInstrumentation = WinstonInstrumentation;
142
174
  //# sourceMappingURL=instrumentation.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentation.js","sourceRoot":"","sources":["../../src/instrumentation.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4CAM4B;AAC5B,oEAMwC;AAQxC,uCAAoC;AAEpC,MAAM,gBAAgB,GAAG,CAAC,QAAQ,CAAC,CAAC;AACpC,MAAM,mBAAmB,GAAG,CAAC,QAAQ,CAAC,CAAC;AAEvC,MAAa,sBAAuB,SAAQ,qCAAmB;IAC7D,YAAY,SAAuC,EAAE;QACnD,KAAK,CAAC,wCAAwC,EAAE,iBAAO,EAAE,MAAM,CAAC,CAAC;IACnE,CAAC;IAES,IAAI;QACZ,OAAO;YACL,IAA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*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n context,\n trace,\n isSpanContextValid,\n Span,\n SpanContext,\n} from '@opentelemetry/api';\nimport {\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n InstrumentationNodeModuleFile,\n isWrapped,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport type { WinstonInstrumentationConfig } from './types';\nimport type {\n Winston2LogMethod,\n Winston2LoggerModule,\n Winston3LogMethod,\n Winston3Logger,\n} from './internal-types';\nimport { VERSION } from './version';\n\nconst winston3Versions = ['>=3 <4'];\nconst winstonPre3Versions = ['>=1 <3'];\n\nexport class WinstonInstrumentation extends InstrumentationBase {\n constructor(config: WinstonInstrumentationConfig = {}) {\n super('@opentelemetry/instrumentation-winston', VERSION, config);\n }\n\n protected init() {\n return [\n new InstrumentationNodeModuleDefinition<{}>(\n 'winston',\n winston3Versions,\n moduleExports => moduleExports,\n () => {},\n [\n new InstrumentationNodeModuleFile<Winston3Logger>(\n 'winston/lib/winston/logger.js',\n winston3Versions,\n (logger, moduleVersion) => {\n this._diag.debug(`Applying patch for winston@${moduleVersion}`);\n if (isWrapped(logger.prototype['write'])) {\n this._unwrap(logger.prototype, 'write');\n }\n\n this._wrap(logger.prototype, 'write', this._getPatchedWrite());\n return logger;\n },\n (logger, moduleVersion) => {\n if (logger === undefined) return;\n this._diag.debug(`Removing patch for winston@${moduleVersion}`);\n this._unwrap(logger.prototype, 'write');\n }\n ),\n ]\n ),\n new InstrumentationNodeModuleDefinition<{}>(\n 'winston',\n winstonPre3Versions,\n moduleExports => moduleExports,\n () => {},\n [\n new InstrumentationNodeModuleFile<Winston2LoggerModule>(\n 'winston/lib/winston/logger.js',\n winstonPre3Versions,\n (fileExports, moduleVersion) => {\n this._diag.debug(`Applying patch for winston@${moduleVersion}`);\n const proto = fileExports.Logger.prototype;\n\n if (isWrapped(proto.log)) {\n this._unwrap(proto, 'log');\n }\n\n this._wrap(proto, 'log', this._getPatchedLog());\n\n return fileExports;\n },\n (fileExports, moduleVersion) => {\n if (fileExports === undefined) return;\n this._diag.debug(`Removing patch for winston@${moduleVersion}`);\n this._unwrap(fileExports.Logger.prototype, 'log');\n }\n ),\n ]\n ),\n ];\n }\n\n override getConfig(): WinstonInstrumentationConfig {\n return this._config;\n }\n\n override setConfig(config: WinstonInstrumentationConfig) {\n this._config = config;\n }\n\n private _callHook(span: Span, record: Record<string, string>) {\n const hook = this.getConfig().logHook;\n\n if (!hook) {\n return;\n }\n\n safeExecuteInTheMiddle(\n () => hook(span, record),\n err => {\n if (err) {\n this._diag.error('error calling logHook', err);\n }\n },\n true\n );\n }\n\n private _getPatchedWrite() {\n return (original: Winston3LogMethod) => {\n const instrumentation = this;\n return function patchedWrite(\n this: never,\n ...args: Parameters<typeof original>\n ) {\n const span = trace.getSpan(context.active());\n\n if (!span) {\n return original.apply(this, args);\n }\n\n const spanContext = span.spanContext();\n\n if (!isSpanContextValid(spanContext)) {\n return original.apply(this, args);\n }\n\n const record = args[0];\n injectRecord(spanContext, record);\n instrumentation._callHook(span, record);\n\n return original.apply(this, args);\n };\n };\n }\n\n private _getPatchedLog() {\n return (original: Winston2LogMethod) => {\n const instrumentation = this;\n return function patchedLog(\n this: unknown,\n ...args: Parameters<typeof original>\n ) {\n const span = trace.getSpan(context.active());\n\n if (!span) {\n return original.apply(this, args);\n }\n\n const spanContext = span.spanContext();\n\n if (!isSpanContextValid(spanContext)) {\n return original.apply(this, args);\n }\n\n for (let i = args.length - 1; i >= 0; i--) {\n if (typeof args[i] === 'object') {\n const record = args[i];\n injectRecord(spanContext, record);\n instrumentation._callHook(span, record);\n return original.apply(this, args);\n }\n }\n\n const record = injectRecord(spanContext);\n\n const insertAt =\n typeof args[args.length - 1] === 'function'\n ? args.length - 1\n : args.length;\n\n args.splice(insertAt, 0, record);\n instrumentation._callHook(span, record);\n\n return original.apply(this, args);\n };\n };\n }\n}\n\nfunction injectRecord(\n spanContext: SpanContext,\n record?: Record<string, string>\n) {\n const fields = {\n trace_id: spanContext.traceId,\n span_id: spanContext.spanId,\n trace_flags: `0${spanContext.traceFlags.toString(16)}`,\n };\n\n if (!record) {\n return fields;\n }\n\n return Object.assign(record, fields);\n}\n"]}
1
+ {"version":3,"file":"instrumentation.js","sourceRoot":"","sources":["../../src/instrumentation.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4CAA8E;AAC9E,oEAMwC;AASxC,uCAAoC;AAEpC,MAAM,gBAAgB,GAAG,CAAC,QAAQ,CAAC,CAAC;AACpC,MAAM,mBAAmB,GAAG,CAAC,QAAQ,CAAC,CAAC;AAEvC,MAAa,sBAAuB,SAAQ,qCAAmB;IAC7D,YAAY,SAAuC,EAAE;QACnD,KAAK,CAAC,wCAAwC,EAAE,iBAAO,EAAE,MAAM,CAAC,CAAC;IACnE,CAAC;IAES,IAAI;QACZ,MAAM,4CAA4C,GAChD,IAAI,qDAAmC,CACrC,SAAS,EACT,gBAAgB,EAChB,aAAa,CAAC,EAAE,CAAC,aAAa,EAC9B,GAAG,EAAE,GAAE,CAAC,EACR;YACE,IAAI,+CAA6B,CAC/B,+BAA+B,EAC/B,gBAAgB,EAChB,CAAC,MAAM,EAAE,aAAa,EAAE,EAAE;gBACxB,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,8BAA8B,aAAa,EAAE,CAAC,CAAC;gBAChE,IAAI,IAAA,2BAAS,EAAC,MAAM,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,EAAE;oBACxC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,SAAS,EAAE,OA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AqB,EAAE;YAC3C,MAAM,IAAI,GAAG,WAAK,CAAC,OAAO,CAAC,aAAO,CAAC,MAAM,EAAE,CAAC,CAAC;YAC7C,IAAI,IAAI,EAAE;gBACR,MAAM,WAAW,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;gBACvC,IAAI,IAAA,wBAAkB,EAAC,WAAW,CAAC,EAAE;oBACnC,MAAM,MAAM,GAAG;wBACb,QAAQ,EAAE,WAAW,CAAC,OAAO;wBAC7B,OAAO,EAAE,WAAW,CAAC,MAAM;wBAC3B,WAAW,EAAE,IAAI,WAAW,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE;qBACvD,CAAC;oBACF,MAAM,cAAc,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;oBACrD,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;oBACrC,OAAO,cAAc,CAAC;iBACvB;aACF;SACF;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AAjND,wDAiNC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { context, trace, isSpanContextValid, Span } from '@opentelemetry/api';\nimport {\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n InstrumentationNodeModuleFile,\n isWrapped,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport type { WinstonInstrumentationConfig } from './types';\nimport type {\n Winston2LogMethod,\n Winston2LoggerModule,\n Winston3ConfigureMethod,\n Winston3LogMethod,\n Winston3Logger,\n} from './internal-types';\nimport { VERSION } from './version';\n\nconst winston3Versions = ['>=3 <4'];\nconst winstonPre3Versions = ['>=1 <3'];\n\nexport class WinstonInstrumentation extends InstrumentationBase {\n constructor(config: WinstonInstrumentationConfig = {}) {\n super('@opentelemetry/instrumentation-winston', VERSION, config);\n }\n\n protected init() {\n const winstons3instrumentationNodeModuleDefinition =\n new InstrumentationNodeModuleDefinition<{}>(\n 'winston',\n winston3Versions,\n moduleExports => moduleExports,\n () => {},\n [\n new InstrumentationNodeModuleFile<Winston3Logger>(\n 'winston/lib/winston/logger.js',\n winston3Versions,\n (logger, moduleVersion) => {\n this._diag.debug(`Applying patch for winston@${moduleVersion}`);\n if (isWrapped(logger.prototype['write'])) {\n this._unwrap(logger.prototype, 'write');\n }\n this._wrap(logger.prototype, 'write', this._getPatchedWrite());\n\n // Wrap configure\n if (isWrapped(logger.prototype['configure'])) {\n this._unwrap(logger.prototype, 'configure');\n }\n this._wrap(\n logger.prototype,\n 'configure',\n this._getPatchedConfigure()\n );\n\n return logger;\n },\n (logger, moduleVersion) => {\n if (logger === undefined) return;\n this._diag.debug(`Removing patch for winston@${moduleVersion}`);\n this._unwrap(logger.prototype, 'write');\n this._unwrap(logger.prototype, 'configure');\n }\n ),\n ]\n );\n\n const winstons2instrumentationNodeModuleDefinition =\n new InstrumentationNodeModuleDefinition<{}>(\n 'winston',\n winstonPre3Versions,\n moduleExports => moduleExports,\n () => {},\n [\n new InstrumentationNodeModuleFile<Winston2LoggerModule>(\n 'winston/lib/winston/logger.js',\n winstonPre3Versions,\n (fileExports, moduleVersion) => {\n this._diag.debug(`Applying patch for winston@${moduleVersion}`);\n const proto = fileExports.Logger.prototype;\n\n if (isWrapped(proto.log)) {\n this._unwrap(proto, 'log');\n }\n this._wrap(proto, 'log', this._getPatchedLog());\n\n return fileExports;\n },\n (fileExports, moduleVersion) => {\n if (fileExports === undefined) return;\n this._diag.debug(`Removing patch for winston@${moduleVersion}`);\n this._unwrap(fileExports.Logger.prototype, 'log');\n }\n ),\n ]\n );\n return [\n winstons3instrumentationNodeModuleDefinition,\n winstons2instrumentationNodeModuleDefinition,\n ];\n }\n\n override getConfig(): WinstonInstrumentationConfig {\n return this._config;\n }\n\n override setConfig(config: WinstonInstrumentationConfig) {\n this._config = config;\n }\n\n private _callHook(span: Span, record: Record<string, string>) {\n const hook = this.getConfig().logHook;\n\n if (!hook) {\n return;\n }\n\n safeExecuteInTheMiddle(\n () => hook(span, record),\n err => {\n if (err) {\n this._diag.error('error calling logHook', err);\n }\n },\n true\n );\n }\n\n private _getPatchedWrite() {\n return (original: Winston3LogMethod) => {\n const instrumentation = this;\n return function patchedWrite(\n this: never,\n ...args: Parameters<typeof original>\n ) {\n const record = args[0];\n instrumentation._handleLogCorrelation(record);\n return original.apply(this, args);\n };\n };\n }\n\n private _getPatchedLog() {\n return (original: Winston2LogMethod) => {\n const instrumentation = this;\n return function patchedLog(\n this: never,\n ...args: Parameters<typeof original>\n ) {\n const record: Record<string, any> = {};\n instrumentation._handleLogCorrelation(record);\n // Inject in metadata argument\n let isDataInjected = false;\n for (let i = args.length - 1; i >= 0; i--) {\n if (typeof args[i] === 'object') {\n args[i] = Object.assign(args[i], record);\n isDataInjected = true;\n break;\n }\n }\n if (!isDataInjected) {\n const insertAt =\n typeof args[args.length - 1] === 'function'\n ? args.length - 1\n : args.length;\n\n args.splice(insertAt, 0, record);\n }\n\n return original.apply(this, args);\n };\n };\n }\n\n private _getPatchedConfigure() {\n return (original: Winston3ConfigureMethod) => {\n const instrumentation = this;\n return function patchedConfigure(\n this: never,\n ...args: Parameters<typeof original>\n ) {\n const config = instrumentation.getConfig();\n if (!config.disableLogSending) {\n if (args && args.length > 0) {\n // Try to load Winston transport\n try {\n const {\n OpenTelemetryTransportV3,\n } = require('@opentelemetry/winston-transport');\n const originalTransports = args[0].transports;\n let newTransports = Array.isArray(originalTransports)\n ? originalTransports\n : [];\n const openTelemetryTransport = new OpenTelemetryTransportV3();\n if (originalTransports && !Array.isArray(originalTransports)) {\n newTransports = [originalTransports];\n }\n newTransports.push(openTelemetryTransport);\n args[0].transports = newTransports;\n } catch (err) {\n instrumentation._diag.warn(\n 'OpenTelemetry Winston transport is not available, log records will not be automatically sent.',\n err\n );\n }\n }\n }\n return original.apply(this, args);\n };\n };\n }\n\n private _handleLogCorrelation(record: Record<string, string>) {\n if (!this.getConfig().disableLogCorrelation) {\n const span = trace.getSpan(context.active());\n if (span) {\n const spanContext = span.spanContext();\n if (isSpanContextValid(spanContext)) {\n const fields = {\n trace_id: spanContext.traceId,\n span_id: spanContext.spanId,\n trace_flags: `0${spanContext.traceFlags.toString(16)}`,\n };\n const enhancedRecord = Object.assign(record, fields);\n this._callHook(span, enhancedRecord);\n return enhancedRecord;\n }\n }\n }\n return record;\n }\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import type { Logger as Winston3Logger } from 'winston';
2
2
  import type { LoggerInstance as Winston2Logger, LogMethod as Winston2LogMethod } from 'winston2';
3
3
  export declare type Winston3LogMethod = Winston3Logger['write'];
4
+ export declare type Winston3ConfigureMethod = Winston3Logger['configure'];
4
5
  export type { Winston3Logger };
5
6
  export type { Winston2LogMethod };
6
7
  export declare type Winston2LoggerModule = {
@@ -1 +1 @@
1
- {"version":3,"file":"internal-types.js","sourceRoot":"","sources":["../../src/internal-types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Logger as Winston3Logger } from 'winston';\nimport type {\n LoggerInstance as Winston2Logger,\n LogMethod as Winston2LogMethod,\n} from 'winston2';\nexport type Winston3LogMethod = Winston3Logger['write'];\nexport type { Winston3Logger };\n\nexport type { Winston2LogMethod };\nexport type Winston2LoggerModule = {\n Logger: Winston2Logger & { prototype: { log: Winston2LogMethod } };\n};\nexport type { Winston2Logger };\n"]}
1
+ {"version":3,"file":"internal-types.js","sourceRoot":"","sources":["../../src/internal-types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Logger as Winston3Logger } from 'winston';\nimport type {\n LoggerInstance as Winston2Logger,\n LogMethod as Winston2LogMethod,\n} from 'winston2';\nexport type Winston3LogMethod = Winston3Logger['write'];\nexport type Winston3ConfigureMethod = Winston3Logger['configure'];\nexport type { Winston3Logger };\n\nexport type { Winston2LogMethod };\nexport type Winston2LoggerModule = {\n Logger: Winston2Logger & {\n prototype: { log: Winston2LogMethod };\n };\n};\nexport type { Winston2Logger };\n"]}
@@ -2,6 +2,23 @@ import { Span } from '@opentelemetry/api';
2
2
  import { InstrumentationConfig } from '@opentelemetry/instrumentation';
3
3
  export declare type LogHookFunction = (span: Span, record: Record<string, any>) => void;
4
4
  export interface WinstonInstrumentationConfig extends InstrumentationConfig {
5
+ /**
6
+ * Whether to disable the automatic sending of log records to the
7
+ * OpenTelemetry Logs SDK.
8
+ * @default false
9
+ */
10
+ disableLogSending?: boolean;
11
+ /**
12
+ * Whether to disable the injection trace-context fields, and possibly other
13
+ * fields from `logHook()`, into log records for log correlation.
14
+ * @default false
15
+ */
16
+ disableLogCorrelation?: boolean;
17
+ /**
18
+ * A function that allows injecting additional fields in log records. It is
19
+ * called, as `logHook(span, record)`, for each log record emitted in a valid
20
+ * span context. It requires `disableLogCorrelation` to be false.
21
+ */
5
22
  logHook?: LogHookFunction;
6
23
  }
7
24
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Span } from '@opentelemetry/api';\nimport { InstrumentationConfig } from '@opentelemetry/instrumentation';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type LogHookFunction = (span: Span, record: Record<string, any>) => void;\n\nexport interface WinstonInstrumentationConfig extends InstrumentationConfig {\n logHook?: LogHookFunction;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Span } from '@opentelemetry/api';\nimport { InstrumentationConfig } from '@opentelemetry/instrumentation';\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type LogHookFunction = (span: Span, record: Record<string, any>) => void;\n\nexport interface WinstonInstrumentationConfig extends InstrumentationConfig {\n /**\n * Whether to disable the automatic sending of log records to the\n * OpenTelemetry Logs SDK.\n * @default false\n */\n disableLogSending?: boolean;\n\n /**\n * Whether to disable the injection trace-context fields, and possibly other\n * fields from `logHook()`, into log records for log correlation.\n * @default false\n */\n disableLogCorrelation?: boolean;\n\n /**\n * A function that allows injecting additional fields in log records. It is\n * called, as `logHook(span, record)`, for each log record emitted in a valid\n * span context. It requires `disableLogCorrelation` to be false.\n */\n logHook?: LogHookFunction;\n}\n"]}
@@ -1,2 +1,2 @@
1
- export declare const VERSION = "0.35.0";
1
+ export declare const VERSION = "0.36.0";
2
2
  //# sourceMappingURL=version.d.ts.map
@@ -17,5 +17,5 @@
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.VERSION = void 0;
19
19
  // this is autogenerated file, see scripts/version-update.js
20
- exports.VERSION = '0.35.0';
20
+ exports.VERSION = '0.36.0';
21
21
  //# sourceMappingURL=version.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4DAA4D;AAC/C,QAAA,OAAO,GAAG,QAAQ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '0.35.0';\n"]}
1
+ {"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4DAA4D;AAC/C,QAAA,OAAO,GAAG,QAAQ,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const VERSION = '0.36.0';\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opentelemetry/instrumentation-winston",
3
- "version": "0.35.0",
3
+ "version": "0.36.0",
4
4
  "description": "OpenTelemetry instrumentation for winston",
5
5
  "main": "build/src/index.js",
6
6
  "types": "build/src/index.d.ts",
@@ -45,9 +45,10 @@
45
45
  },
46
46
  "devDependencies": {
47
47
  "@opentelemetry/api": "^1.3.0",
48
- "@opentelemetry/context-async-hooks": "^1.8.0",
49
- "@opentelemetry/sdk-trace-base": "^1.8.0",
50
- "@opentelemetry/sdk-trace-node": "^1.8.0",
48
+ "@opentelemetry/context-async-hooks": "^1.21.0",
49
+ "@opentelemetry/sdk-trace-base": "^1.21.0",
50
+ "@opentelemetry/sdk-trace-node": "^1.21.0",
51
+ "@opentelemetry/winston-transport": "^0.2.0",
51
52
  "@types/mocha": "7.0.2",
52
53
  "@types/node": "18.6.5",
53
54
  "@types/sinon": "10.0.18",
@@ -56,15 +57,15 @@
56
57
  "nyc": "15.1.0",
57
58
  "rimraf": "5.0.5",
58
59
  "sinon": "15.2.0",
59
- "test-all-versions": "6.0.0",
60
+ "test-all-versions": "6.1.0",
60
61
  "ts-mocha": "10.0.0",
61
62
  "typescript": "4.4.4",
62
63
  "winston": "3.3.3",
63
64
  "winston2": "npm:winston@2.4.7"
64
65
  },
65
66
  "dependencies": {
66
- "@opentelemetry/instrumentation": "^0.49.1"
67
+ "@opentelemetry/instrumentation": "^0.50.0"
67
68
  },
68
69
  "homepage": "https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-winston#readme",
69
- "gitHead": "fcea8ca0c83cb1dcd8ac736e5ea4d22ff20dc982"
70
+ "gitHead": "17a0bc1da3baa472ba9b867eee3c60730cc130fb"
70
71
  }