Socket
Socket
Sign inDemoInstall

@opentelemetry/instrumentation-winston

Package Overview
Dependencies
Maintainers
3
Versions
33
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@opentelemetry/instrumentation-winston - npm Package Compare versions

Comparing version 0.35.0 to 0.36.0

2

build/src/instrumentation.d.ts

@@ -11,3 +11,5 @@ import { InstrumentationBase, InstrumentationNodeModuleDefinition } from '@opentelemetry/instrumentation';

private _getPatchedLog;
private _getPatchedConfigure;
private _handleLogCorrelation;
}
//# sourceMappingURL=instrumentation.d.ts.map

172

build/src/instrumentation.js

@@ -29,34 +29,42 @@ "use strict";

init() {
const winstons3instrumentationNodeModuleDefinition = new instrumentation_1.InstrumentationNodeModuleDefinition('winston', winston3Versions, moduleExports => moduleExports, () => { }, [
new instrumentation_1.InstrumentationNodeModuleFile('winston/lib/winston/logger.js', winston3Versions, (logger, moduleVersion) => {
this._diag.debug(`Applying patch for winston@${moduleVersion}`);
if ((0, instrumentation_1.isWrapped)(logger.prototype['write'])) {
this._unwrap(logger.prototype, 'write');
}
this._wrap(logger.prototype, 'write', this._getPatchedWrite());
// Wrap configure
if ((0, instrumentation_1.isWrapped)(logger.prototype['configure'])) {
this._unwrap(logger.prototype, 'configure');
}
this._wrap(logger.prototype, 'configure', this._getPatchedConfigure());
return logger;
}, (logger, moduleVersion) => {
if (logger === undefined)
return;
this._diag.debug(`Removing patch for winston@${moduleVersion}`);
this._unwrap(logger.prototype, 'write');
this._unwrap(logger.prototype, 'configure');
}),
]);
const winstons2instrumentationNodeModuleDefinition = new instrumentation_1.InstrumentationNodeModuleDefinition('winston', winstonPre3Versions, moduleExports => moduleExports, () => { }, [
new instrumentation_1.InstrumentationNodeModuleFile('winston/lib/winston/logger.js', winstonPre3Versions, (fileExports, moduleVersion) => {
this._diag.debug(`Applying patch for winston@${moduleVersion}`);
const proto = fileExports.Logger.prototype;
if ((0, instrumentation_1.isWrapped)(proto.log)) {
this._unwrap(proto, 'log');
}
this._wrap(proto, 'log', this._getPatchedLog());
return fileExports;
}, (fileExports, moduleVersion) => {
if (fileExports === undefined)
return;
this._diag.debug(`Removing patch for winston@${moduleVersion}`);
this._unwrap(fileExports.Logger.prototype, 'log');
}),
]);
return [
new instrumentation_1.InstrumentationNodeModuleDefinition('winston', winston3Versions, moduleExports => moduleExports, () => { }, [
new instrumentation_1.InstrumentationNodeModuleFile('winston/lib/winston/logger.js', winston3Versions, (logger, moduleVersion) => {
this._diag.debug(`Applying patch for winston@${moduleVersion}`);
if ((0, instrumentation_1.isWrapped)(logger.prototype['write'])) {
this._unwrap(logger.prototype, 'write');
}
this._wrap(logger.prototype, 'write', this._getPatchedWrite());
return logger;
}, (logger, moduleVersion) => {
if (logger === undefined)
return;
this._diag.debug(`Removing patch for winston@${moduleVersion}`);
this._unwrap(logger.prototype, 'write');
}),
]),
new instrumentation_1.InstrumentationNodeModuleDefinition('winston', winstonPre3Versions, moduleExports => moduleExports, () => { }, [
new instrumentation_1.InstrumentationNodeModuleFile('winston/lib/winston/logger.js', winstonPre3Versions, (fileExports, moduleVersion) => {
this._diag.debug(`Applying patch for winston@${moduleVersion}`);
const proto = fileExports.Logger.prototype;
if ((0, instrumentation_1.isWrapped)(proto.log)) {
this._unwrap(proto, 'log');
}
this._wrap(proto, 'log', this._getPatchedLog());
return fileExports;
}, (fileExports, moduleVersion) => {
if (fileExports === undefined)
return;
this._diag.debug(`Removing patch for winston@${moduleVersion}`);
this._unwrap(fileExports.Logger.prototype, 'log');
}),
]),
winstons3instrumentationNodeModuleDefinition,
winstons2instrumentationNodeModuleDefinition,
];

@@ -85,13 +93,4 @@ }

return function patchedWrite(...args) {
const span = api_1.trace.getSpan(api_1.context.active());
if (!span) {
return original.apply(this, args);
}
const spanContext = span.spanContext();
if (!(0, api_1.isSpanContextValid)(spanContext)) {
return original.apply(this, args);
}
const record = args[0];
injectRecord(spanContext, record);
instrumentation._callHook(span, record);
instrumentation._handleLogCorrelation(record);
return original.apply(this, args);

@@ -105,24 +104,19 @@ };

return function patchedLog(...args) {
const span = api_1.trace.getSpan(api_1.context.active());
if (!span) {
return original.apply(this, args);
}
const spanContext = span.spanContext();
if (!(0, api_1.isSpanContextValid)(spanContext)) {
return original.apply(this, args);
}
const record = {};
instrumentation._handleLogCorrelation(record);
// Inject in metadata argument
let isDataInjected = false;
for (let i = args.length - 1; i >= 0; i--) {
if (typeof args[i] === 'object') {
const record = args[i];
injectRecord(spanContext, record);
instrumentation._callHook(span, record);
return original.apply(this, args);
args[i] = Object.assign(args[i], record);
isDataInjected = true;
break;
}
}
const record = injectRecord(spanContext);
const insertAt = typeof args[args.length - 1] === 'function'
? args.length - 1
: args.length;
args.splice(insertAt, 0, record);
instrumentation._callHook(span, record);
if (!isDataInjected) {
const insertAt = typeof args[args.length - 1] === 'function'
? args.length - 1
: args.length;
args.splice(insertAt, 0, record);
}
return original.apply(this, args);

@@ -132,15 +126,53 @@ };

}
_getPatchedConfigure() {
return (original) => {
const instrumentation = this;
return function patchedConfigure(...args) {
const config = instrumentation.getConfig();
if (!config.disableLogSending) {
if (args && args.length > 0) {
// Try to load Winston transport
try {
const { OpenTelemetryTransportV3, } = require('@opentelemetry/winston-transport');
const originalTransports = args[0].transports;
let newTransports = Array.isArray(originalTransports)
? originalTransports
: [];
const openTelemetryTransport = new OpenTelemetryTransportV3();
if (originalTransports && !Array.isArray(originalTransports)) {
newTransports = [originalTransports];
}
newTransports.push(openTelemetryTransport);
args[0].transports = newTransports;
}
catch (err) {
instrumentation._diag.warn('OpenTelemetry Winston transport is not available, log records will not be automatically sent.', err);
}
}
}
return original.apply(this, args);
};
};
}
_handleLogCorrelation(record) {
if (!this.getConfig().disableLogCorrelation) {
const span = api_1.trace.getSpan(api_1.context.active());
if (span) {
const spanContext = span.spanContext();
if ((0, api_1.isSpanContextValid)(spanContext)) {
const fields = {
trace_id: spanContext.traceId,
span_id: spanContext.spanId,
trace_flags: `0${spanContext.traceFlags.toString(16)}`,
};
const enhancedRecord = Object.assign(record, fields);
this._callHook(span, enhancedRecord);
return enhancedRecord;
}
}
}
return record;
}
}
exports.WinstonInstrumentation = WinstonInstrumentation;
function injectRecord(spanContext, record) {
const fields = {
trace_id: spanContext.traceId,
span_id: spanContext.spanId,
trace_flags: `0${spanContext.traceFlags.toString(16)}`,
};
if (!record) {
return fields;
}
return Object.assign(record, fields);
}
//# sourceMappingURL=instrumentation.js.map
import type { Logger as Winston3Logger } from 'winston';
import type { LoggerInstance as Winston2Logger, LogMethod as Winston2LogMethod } from 'winston2';
export declare type Winston3LogMethod = Winston3Logger['write'];
export declare type Winston3ConfigureMethod = Winston3Logger['configure'];
export type { Winston3Logger };

@@ -5,0 +6,0 @@ export type { Winston2LogMethod };

@@ -5,4 +5,21 @@ import { Span } from '@opentelemetry/api';

export interface WinstonInstrumentationConfig extends InstrumentationConfig {
/**
* Whether to disable the automatic sending of log records to the
* OpenTelemetry Logs SDK.
* @default false
*/
disableLogSending?: boolean;
/**
* Whether to disable the injection trace-context fields, and possibly other
* fields from `logHook()`, into log records for log correlation.
* @default false
*/
disableLogCorrelation?: boolean;
/**
* A function that allows injecting additional fields in log records. It is
* called, as `logHook(span, record)`, for each log record emitted in a valid
* span context. It requires `disableLogCorrelation` to be false.
*/
logHook?: LogHookFunction;
}
//# sourceMappingURL=types.d.ts.map

@@ -1,2 +0,2 @@

export declare const VERSION = "0.35.0";
export declare const VERSION = "0.36.0";
//# sourceMappingURL=version.d.ts.map

@@ -20,3 +20,3 @@ "use strict";

// this is autogenerated file, see scripts/version-update.js
exports.VERSION = '0.35.0';
exports.VERSION = '0.36.0';
//# sourceMappingURL=version.js.map
{
"name": "@opentelemetry/instrumentation-winston",
"version": "0.35.0",
"version": "0.36.0",
"description": "OpenTelemetry instrumentation for winston",

@@ -48,5 +48,6 @@ "main": "build/src/index.js",

"@opentelemetry/api": "^1.3.0",
"@opentelemetry/context-async-hooks": "^1.8.0",
"@opentelemetry/sdk-trace-base": "^1.8.0",
"@opentelemetry/sdk-trace-node": "^1.8.0",
"@opentelemetry/context-async-hooks": "^1.21.0",
"@opentelemetry/sdk-trace-base": "^1.21.0",
"@opentelemetry/sdk-trace-node": "^1.21.0",
"@opentelemetry/winston-transport": "^0.2.0",
"@types/mocha": "7.0.2",

@@ -60,3 +61,3 @@ "@types/node": "18.6.5",

"sinon": "15.2.0",
"test-all-versions": "6.0.0",
"test-all-versions": "6.1.0",
"ts-mocha": "10.0.0",

@@ -68,6 +69,6 @@ "typescript": "4.4.4",

"dependencies": {
"@opentelemetry/instrumentation": "^0.49.1"
"@opentelemetry/instrumentation": "^0.50.0"
},
"homepage": "https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-winston#readme",
"gitHead": "fcea8ca0c83cb1dcd8ac736e5ea4d22ff20dc982"
"gitHead": "17a0bc1da3baa472ba9b867eee3c60730cc130fb"
}

@@ -6,3 +6,3 @@ # OpenTelemetry instrumentation for winston

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.
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.

@@ -23,19 +23,28 @@ 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.

const { NodeTracerProvider } = require('@opentelemetry/sdk-trace-node');
const logsAPI = require('@opentelemetry/api-logs');
const {
LoggerProvider,
SimpleLogRecordProcessor,
ConsoleLogRecordExporter,
} = require('@opentelemetry/sdk-logs');
const { WinstonInstrumentation } = require('@opentelemetry/instrumentation-winston');
const { registerInstrumentations } = require('@opentelemetry/instrumentation');
const provider = new NodeTracerProvider();
provider.register();
const tracerProvider = new NodeTracerProvider();
tracerProvider.register();
// To start a logger, you first need to initialize the Logger provider.
const loggerProvider = new LoggerProvider();
// Add a processor to export log record
loggerProvider.addLogRecordProcessor(
new SimpleLogRecordProcessor(new ConsoleLogRecordExporter())
);
logsAPI.logs.setGlobalLoggerProvider(loggerProvider);
registerInstrumentations({
instrumentations: [
new WinstonInstrumentation({
// Optional hook to insert additional context to log metadata.
// Called after trace context is injected to metadata.
logHook: (span, record) => {
record['resource.service.name'] = provider.resource.attributes['service.name'];
},
}),
// other instrumentations
],
instrumentations: [
new WinstonInstrumentation({
// See below for Winston instrumentation options.
}),
],
});

@@ -45,3 +54,3 @@

const logger = winston.createLogger({
transports: [new winston.transports.Console()],
transports: [new winston.transports.Console()],
})

@@ -52,6 +61,30 @@ logger.info('foobar');

### Fields added to Winston metadata
### Winston instrumentation options
For the current active span, the following fields are injected:
| Option | Type | Description |
| ----------------------- | ----------------- | ----------- |
| `disableLogSending` | `boolean` | Whether to disable [log sending](#log-sending). Default `false`. |
| `disableLogCorrelation` | `boolean` | Whether to disable [log correlation](#log-correlation). Default `false`. |
| `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. |
### Log sending
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.
If the OpenTelemetry SDK is not configured with a Logger provider, then this will be a no-op.
Log sending can be disabled with the `disableLogSending: true` option. Log sending is only available for Winston version 3 and later.
```bash
npm install --save @opentelemetry/winston-transport
```
### Log correlation
Winston logger calls in the context of a tracing span will have fields
indentifying the span added to the log record. This allows
[correlating](https://opentelemetry.io/docs/specs/otel/logs/#log-correlation)
log records with tracing data. The added fields are
([spec](https://opentelemetry.io/docs/specs/otel/compatibility/logging_trace_context/)):
* `trace_id`

@@ -61,4 +94,12 @@ * `span_id`

When no span context is active or the span context is invalid, injection is skipped.
After adding these fields, the optional `logHook` is called to allow injecting additional fields. For example:
```js
logHook: (span, record) => {
record['resource.service.name'] = provider.resource.attributes['service.name'];
}
```
Log injection can be disabled with the `disableLogCorrelation: true` option.
### Supported versions

@@ -68,2 +109,6 @@

Log sending
`3.x`
## Useful links

@@ -70,0 +115,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc