Socket
Socket
Sign inDemoInstall

@opentelemetry/instrumentation-bunyan

Package Overview
Dependencies
Maintainers
3
Versions
32
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@opentelemetry/instrumentation-bunyan - npm Package Compare versions

Comparing version 0.33.0 to 0.34.0

build/src/OpenTelemetryBunyanStream.d.ts

1

build/src/index.d.ts
export * from './instrumentation';
export * from './types';
export * from './OpenTelemetryBunyanStream';
//# sourceMappingURL=index.d.ts.map

@@ -30,2 +30,3 @@ "use strict";

__exportStar(require("./types"), exports);
__exportStar(require("./OpenTelemetryBunyanStream"), exports);
//# sourceMappingURL=index.js.map

@@ -10,4 +10,6 @@ import { InstrumentationBase, InstrumentationNodeModuleDefinition } from '@opentelemetry/instrumentation';

private _getPatchedEmit;
private _getPatchedCreateLogger;
private _addStream;
private _callHook;
}
//# sourceMappingURL=instrumentation.d.ts.map

@@ -19,28 +19,55 @@ "use strict";

exports.BunyanInstrumentation = void 0;
const util_1 = require("util");
const api_1 = require("@opentelemetry/api");
const instrumentation_1 = require("@opentelemetry/instrumentation");
const version_1 = require("./version");
const OpenTelemetryBunyanStream_1 = require("./OpenTelemetryBunyanStream");
const DEFAULT_CONFIG = {
disableLogSending: false,
disableLogCorrelation: false,
};
class BunyanInstrumentation extends instrumentation_1.InstrumentationBase {
constructor(config = {}) {
super('@opentelemetry/instrumentation-bunyan', version_1.VERSION, config);
super('@opentelemetry/instrumentation-bunyan', version_1.VERSION, Object.assign({}, DEFAULT_CONFIG, config));
}
init() {
return [
new instrumentation_1.InstrumentationNodeModuleDefinition('bunyan', ['<2.0'], (logger, moduleVersion) => {
new instrumentation_1.InstrumentationNodeModuleDefinition('bunyan', ['<2.0'], (module, moduleVersion) => {
this._diag.debug(`Applying patch for bunyan@${moduleVersion}`);
const instrumentation = this;
const Logger = module[Symbol.toStringTag] === 'Module'
? module.default // ESM
: module; // CommonJS
this._wrap(Logger.prototype, '_emit',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const proto = logger.prototype;
if ((0, instrumentation_1.isWrapped)(proto['_emit'])) {
this._unwrap(proto, '_emit');
this._getPatchedEmit());
function LoggerTraced(...args) {
let inst;
let retval = undefined;
if (this instanceof LoggerTraced) {
// called with `new Logger()`
inst = this;
Logger.apply(this, args);
}
else {
// called without `new`
inst = Logger(...args);
retval = inst;
}
// If `_childOptions` is defined, this is a `Logger#child(...)`
// call. We must not add an OTel stream again.
if (args[1] /* _childOptions */ === undefined) {
instrumentation._addStream(inst);
}
return retval;
}
this._wrap(proto, '_emit',
// Must use the deprecated `inherits` to support this style:
// const log = require('bunyan')({name: 'foo'});
// i.e. calling the constructor function without `new`.
(0, util_1.inherits)(LoggerTraced, Logger);
const patchedExports = Object.assign(LoggerTraced, Logger);
this._wrap(patchedExports, 'createLogger',
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this._getPatchedEmit());
return logger;
}, (logger, moduleVersion) => {
if (logger === undefined)
return;
this._diag.debug(`Removing patch for bunyan@${moduleVersion}`);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
this._unwrap(logger.prototype, '_emit');
this._getPatchedCreateLogger());
return patchedExports;
}),

@@ -53,3 +80,3 @@ ];

setConfig(config) {
this._config = config;
this._config = Object.assign({}, DEFAULT_CONFIG, config);
}

@@ -60,2 +87,6 @@ _getPatchedEmit() {

return function patchedEmit(...args) {
const config = instrumentation.getConfig();
if (!instrumentation.isEnabled() || config.disableLogCorrelation) {
return original.apply(this, args);
}
const span = api_1.trace.getSpan(api_1.context.active());

@@ -78,2 +109,24 @@ if (!span) {

}
_getPatchedCreateLogger() {
return (original) => {
const instrumentation = this;
return function patchedCreateLogger(...args) {
const logger = original(...args);
instrumentation._addStream(logger);
return logger;
};
};
}
_addStream(logger) {
const config = this.getConfig();
if (!this.isEnabled() || config.disableLogSending) {
return;
}
this._diag.debug('Adding OpenTelemetryBunyanStream to logger');
logger.addStream({
type: 'raw',
stream: new OpenTelemetryBunyanStream_1.OpenTelemetryBunyanStream(),
level: logger.level(),
});
}
_callHook(span, record) {

@@ -80,0 +133,0 @@ const hook = this.getConfig().logHook;

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

export interface BunyanInstrumentationConfig 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

2

build/src/version.d.ts

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

export declare const VERSION = "0.33.0";
export declare const VERSION = "0.34.0";
//# sourceMappingURL=version.d.ts.map

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

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

@@ -15,3 +15,3 @@ "main": "build/src/index.js",

"prewatch": "npm run precompile",
"prepare": "npm run compile",
"prepublishOnly": "npm run compile",
"tdd": "npm run test -- --watch-extensions ts --watch",

@@ -49,5 +49,7 @@ "test": "nyc ts-mocha -p tsconfig.json 'test/**/*.test.ts'",

"@opentelemetry/api": "^1.3.0",
"@opentelemetry/context-async-hooks": "^1.8.0",
"@opentelemetry/resources": "^1.8.0",
"@opentelemetry/sdk-logs": "^0.45.1",
"@opentelemetry/sdk-trace-base": "^1.8.0",
"@opentelemetry/sdk-trace-node": "^1.8.0",
"@opentelemetry/semantic-conventions": "^1.0.0",
"@types/mocha": "7.0.2",

@@ -66,2 +68,3 @@ "@types/node": "18.6.5",

"dependencies": {
"@opentelemetry/api-logs": "^0.45.1",
"@opentelemetry/instrumentation": "^0.45.1",

@@ -71,3 +74,3 @@ "@types/bunyan": "1.8.9"

"homepage": "https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-bunyan#readme",
"gitHead": "607d375595da3ab51b7f773ac360900121c4361b"
"gitHead": "c7e7000b7bf79b0b107c448b403c2613a9b9e2c1"
}

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

This module provides automatic instrumentation for the injection of trace context to [`bunyan`](https://www.npmjs.com/package/bunyan), 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 [`bunyan`](https://www.npmjs.com/package/bunyan) module to inject trace-context into Bunyan log records (log correlation) and to send Bunyan 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.

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

### Supported Versions
## Supported Versions
- `^1.0.0`
- `bunyan@^1.0.0`

@@ -27,30 +27,46 @@ ## Usage

```js
const { NodeTracerProvider } = require('@opentelemetry/sdk-trace-node');
const { NodeSDK, tracing, logs, api } = require('@opentelemetry/sdk-node');
const { BunyanInstrumentation } = require('@opentelemetry/instrumentation-bunyan');
const { registerInstrumentations } = require('@opentelemetry/instrumentation');
const provider = new NodeTracerProvider();
provider.register();
registerInstrumentations({
const sdk = new NodeSDK({
spanProcessor: new tracing.SimpleSpanProcessor(new tracing.ConsoleSpanExporter()),
logRecordProcessor: new logs.SimpleLogRecordProcessor(new logs.ConsoleLogRecordExporter()),
instrumentations: [
new BunyanInstrumentation({
// Optional hook to insert additional context to bunyan records.
// Called after trace context is added to the record.
logHook: (span, record) => {
record['resource.service.name'] = provider.resource.attributes['service.name'];
},
// See below for Bunyan instrumentation options.
}),
// other instrumentations
],
});
]
})
bunyan.createLogger({ name: 'example' }).info('foo');
// {"name":"example","msg":"foo","trace_id":"e21c7a95fff34e04f77c7bd518779621","span_id":"b7589a981fde09f4","trace_flags":"01", ...}
const bunyan = require('bunyan');
const logger = bunyan.createLogger({name: 'example'});
logger.info('hi');
// 1. Log records will be sent to the SDK-registered log record processor, if any.
// This is called "log sending".
const tracer = api.trace.getTracer('example');
tracer.startActiveSpan('manual-span', span => {
logger.info('in a span');
// 2. Fields identifying the current span will be added to log records:
// {"name":"example",...,"msg":"in a span","trace_id":"d61b4e4af1032e0aae279d12f3ab0159","span_id":"d140da862204f2a2","trace_flags":"01"}
// This is called "log correlation".
})
```
### Fields added to bunyan records
### Log sending
For the current active span, the following will be added to the bunyan record:
Creation of a Bunyan Logger will automatically add a [Bunyan stream](https://github.com/trentm/node-bunyan#streams) that sends log records to the OpenTelemetry Logs SDK. 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 added stream will be a no-op.
Log sending can be disabled with the `disableLogSending: true` option.
### Log correlation
Bunyan 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`

@@ -60,4 +76,48 @@ - `span_id`

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'];
}
```
When no span context is active or the span context is invalid, injection is skipped.
Log injection can be disabled with the `disableLogCorrelation: true` option.
### Bunyan instrumentation options
| 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. |
### Using OpenTelemetryBunyanStream without instrumentation
This package exports the Bunyan stream class that is used to send records to the
OpenTelemetry Logs SDK. It can be used directly when configuring a Bunyan logger
if one is not using the `BunyanInstrumentation` for whatever reason. For
example:
```js
const { OpenTelemetryBunyanStream } = require('@opentelemetry/instrumentation-bunyan');
const bunyan = require('bunyan');
// You must register an OpenTelemetry LoggerProvider, otherwise log records will
// be sent to a no-op implementation. "examples/telemetry.js" shows one way
// to configure one.
// ...
const logger = bunyan.createLogger({
name: 'my-logger',
streams: [
{
type: 'raw',
stream: new OpenTelemetryBunyanStream()
}
],
});
```
## Useful links

@@ -64,0 +124,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