Skip to content

Commit

Permalink
[Feature] otel context injection (#133)
Browse files Browse the repository at this point in the history
* Add `_addOpentelemetryContext()`

* update dependencies

* Add unit tests

* Update dependencies

* Update log

* Add `addOtelContext` configuration option

* docs

* refactor tests
  • Loading branch information
yotamloe authored Dec 24, 2024
1 parent 540ad6f commit aa64f08
Show file tree
Hide file tree
Showing 5 changed files with 335 additions and 29 deletions.
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ logger.log(obj);
* **compress** - If true the the logs are compressed in gzip format. Default: `false`
* **internalLogger** - set internal logger that supports the function log. Default: console.
* **extraFields** - Adds your own custom fields to each log. Add in JSON Format, for example: `extraFields : { field_1: "val_1", field_2: "val_2" , ... }`.
* **addOtelContext** - Add `trace_id`, `span_id`, `service_name` fields to logs when opentelemetry context is available. Default: `true`


## Using UDP
Expand Down Expand Up @@ -99,6 +100,17 @@ logger.log('This is a log message');
}
```

## Add opentelemetry context
If you're sending traces with OpenTelemetry instrumentation (auto or manual), you can correlate your logs with the trace context. That way, your logs will have traces data in it, such as service name, span id and trace id (version >= `2.2.0`). This feature is enabled by default, To disable it, set the `AddOtelContext` param in your handler configuration to `false`, like in this example:

```javascript
var logger = require('logzio-nodejs').createLogger({
token: 'token',
type: 'no-otel-context',
addOtelContext: false
});
```

## Build and test locally
1. Clone the repository:
```bash
Expand All @@ -112,6 +124,10 @@ logger.log('This is a log message');
```

## Update log
**2.2.0**
- Add `addOtelContext` configuration option:
- `trace_id`, `span_id`, `service_name` fields to logs when opentelemetry context is available.

**2.1.8**
- Make `User-Agent` not optional and add the version to it.

Expand Down
71 changes: 45 additions & 26 deletions lib/logzio-nodejs.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const assign = require('lodash.assign');
const dgram = require('dgram');
const zlib = require('zlib');
const axiosInstance = require('./axiosInstance');

const { trace, context } = require('@opentelemetry/api');

const nanoSecDigits = 9;

Expand Down Expand Up @@ -53,6 +53,7 @@ class LogzioLogger {
protocol = 'http',
port,
timeout,
addOtelContext = true,
sleepUntilNextRetry = 2 * 1000,
callback = this._defaultCallback,
extraFields = {},
Expand Down Expand Up @@ -103,11 +104,13 @@ class LogzioLogger {
this.timeout = timeout;

// build the url for logging

this.messages = [];
this.bulkId = 1;
this.extraFields = extraFields;
this.typeOfIP = 'IPv4';

// OpenTelemetry context
this.addOtelContext = addOtelContext
}

_setProtocol(port) {
Expand Down Expand Up @@ -231,31 +234,47 @@ class LogzioLogger {
}
}
}

/**
* Attach OpenTelemetry context to the log record.
* @param msg - The message (Object) to append the OpenTelemetry context to.
* @private
*/
_addOpentelemetryContext(msg) {
if (!this.addOtelContext) {
return;
}
let span = trace.getSpan(context.active());
if (span) {
msg.trace_id = span.spanContext().traceId;
msg.span_id = span.spanContext().spanId;
msg.service_name = span.resource._attributes['service.name'];
}
}
log(msg, obj) {
if (this.closed === true) {
throw new Error('Logging into a logger that has been closed!');
}
if (![null, undefined].includes(obj)) {
msg += JSON.stringify(obj);
}
if (typeof msg === 'string') {
msg = {
message: msg,
};
}
this._addSourceIP(msg);
msg = assign(msg, this.extraFields);
if (!msg.type) {
msg.type = this.type;
}
this._addTimestamp(msg);

this.messages.push(msg);
if (this.messages.length >= this.bufferSize) {
this._debug('Buffer is full - sending bulk');
this._popMsgsAndSend();
}
if (this.closed === true) {
throw new Error('Logging into a logger that has been closed!');
}
if (![null, undefined].includes(obj)) {
msg += JSON.stringify(obj);
}
if (typeof msg === 'string') {
msg = { message: msg };
}

this._addSourceIP(msg);
msg = assign(msg, this.extraFields);
if (!msg.type) {
msg.type = this.type;
}
this._addTimestamp(msg);
this._addOpentelemetryContext(msg);


this.messages.push(msg);
if (this.messages.length >= this.bufferSize) {
this._debug('Buffer is full - sending bulk');
this._popMsgsAndSend();
}
}

_popMsgsAndSend() {
Expand Down
226 changes: 224 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit aa64f08

Please sign in to comment.