Skip to content

Commit

Permalink
feat(tracing): added hook to integrate with pino logger (#17)
Browse files Browse the repository at this point in the history
* feat(tracing): added hook to integrate with pino logger

* refactor(tracing): simplified building the args for the logfn

* test(tracing): removed code duplication from tests
  • Loading branch information
CptSchnitz committed Apr 21, 2021
1 parent b1226f9 commit 688d67f
Show file tree
Hide file tree
Showing 8 changed files with 152 additions and 16 deletions.
56 changes: 51 additions & 5 deletions package-lock.json

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

6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,17 +45,21 @@
"@opentelemetry/metrics": "^0.18.2",
"@opentelemetry/node": "^0.18.2",
"@opentelemetry/tracing": "^0.18.2",
"@types/pino": "^6.3.7",
"env-var": "^7.0.0"
},
"devDependencies": {
"@commitlint/cli": "^11.0.0",
"@commitlint/config-conventional": "^11.0.0",
"@map-colonies/eslint-config": "^2.2.0",
"@opentelemetry/context-async-hooks": "^0.18.2",
"@types/faker": "^5.5.3",
"@types/jest": "^26.0.19",
"@types/node": "^14.14.12",
"commitlint": "^11.0.0",
"cz-conventional-changelog": "^3.3.0",
"eslint": "^7.8.1",
"faker": "^5.5.3",
"husky": "^4.3.5",
"jest": "^26.6.3",
"jest-create-mock-instance": "^1.1.0",
Expand All @@ -65,6 +69,6 @@
"standard-version": "^9.0.0",
"ts-jest": "^26.4.4",
"ts-node": "^9.1.1",
"typescript": "^3.8.3"
"typescript": "^4.2.4"
}
}
1 change: 1 addition & 0 deletions src/tracing/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { Tracing } from './tracing';
export { logMethod } from './loggerHook';
28 changes: 28 additions & 0 deletions src/tracing/loggerHook.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { getSpan, context } from '@opentelemetry/api';
import { LogFn, Logger } from 'pino';

// ignored because its the same type needed for LogFn
// eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/no-explicit-any
export type LogFnArgs = [obj: object, msg?: string, ...args: any[]] | [msg: string, ...args: any[]];

// disabled because this function signature is required by pino
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export function logMethod(this: Logger, args: LogFnArgs, method: LogFn, level: number): void {
const span = getSpan(context.active());

if (!span) {
method.apply<Logger, LogFnArgs, void>(this, args);
return;
}
const traceObj = { spanId: span.context().spanId, traceId: span.context().traceId };

let logFnArgs: LogFnArgs;
const [firstArg, ...rest] = args;
if (typeof firstArg === 'object') {
logFnArgs = [{ ...firstArg, ...traceObj }, ...rest];
} else {
logFnArgs = [traceObj, firstArg, ...rest];
}

method.apply<Logger, LogFnArgs, void>(this, logFnArgs);
}
3 changes: 2 additions & 1 deletion src/tracing/tracing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { CollectorTraceExporter } from '@opentelemetry/exporter-collector';
import { SimpleSpanProcessor } from '@opentelemetry/tracing';
import { InstrumentationOption, registerInstrumentations } from '@opentelemetry/instrumentation';
import { NoopTracerProvider, Tracer } from '@opentelemetry/api';
import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks';
import { TelemetryBase } from '../common/interfaces';
import { getTracingConfig, TracingConfig } from './config';

Expand Down Expand Up @@ -33,7 +34,7 @@ export class Tracing implements TelemetryBase<Tracer> {

// consider batch processor
this.provider.addSpanProcessor(new SimpleSpanProcessor(exporter));
this.provider.register();
this.provider.register({ contextManager: new AsyncHooksContextManager() });

return this.provider.getTracer(this.tracerName);
}
Expand Down
2 changes: 1 addition & 1 deletion tests/configurations/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ module.exports = {
'default',
['jest-html-reporters', { multipleReportsUnitePath: './reports', pageTitle: 'tests', publicPath: './reports', filename: 'tests.html' }],
],
collectCoverageFrom: ['<rootDir>/src/**/*.ts', '!**/node_modules/**', '!**/vendor/**'],
collectCoverageFrom: ['<rootDir>/src/**/*.ts', '!**/node_modules/**', '!**/vendor/**', '!<rootDir>/src/metrics/meterWrapper.ts'],
coverageDirectory: '<rootDir>/coverage',
coverageReporters: ['text-summary', 'html', 'json'],
coverageThreshold: {
Expand Down
64 changes: 64 additions & 0 deletions tests/tracing/loggerHook.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { trace, context, setSpan, Tracer } from '@opentelemetry/api';
import { NodeTracerProvider } from '@opentelemetry/node';
import * as faker from 'faker';
import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks';
import { LogFn, Logger } from 'pino';
import { logMethod } from '../../src';
import { LogFnArgs } from '../../src/tracing/loggerHook';

describe('#logMethod', () => {
let provider: NodeTracerProvider;
let tracer: Tracer;

beforeAll(() => {
provider = new NodeTracerProvider();
provider.register({ contextManager: new AsyncHooksContextManager() });
tracer = trace.getTracer('test_tracer');
});

afterAll(async () => {
await provider.shutdown();
});

it('should call the method with the same args if tracer is not enabled', () => {
const args = [faker.random.word()] as [string];
const logFn = jest.fn();

logMethod.apply(({} as unknown) as Logger, [args, logFn, 5]);

expect(logFn).toHaveBeenLastCalledWith(...args);
});

it('should add traceId and spanId when logging only msg', () => {
const args = [faker.random.word()] as [string];
const logFn = jest.fn();

const span = tracer.startSpan('test_span');
const ctx = setSpan(context.active(), span);

context.with<[LogFnArgs, LogFn, number], typeof logMethod>(ctx, logMethod, ({} as unknown) as Logger, args, logFn, 5);

span.end();

const { spanId, traceId } = span.context();
expect(logFn).toHaveBeenLastCalledWith({ spanId, traceId }, ...args);
});

it('should add traceId and spanId to the logging only obj', () => {
// pino logfn uses the type object
// eslint-disable-next-line @typescript-eslint/ban-types
const args = [{ test: faker.random.word() }, faker.random.word()] as [object, string];
const logFn = jest.fn();

const span = tracer.startSpan('test_span');
const ctx = setSpan(context.active(), span);

context.with<[LogFnArgs, LogFn, number], typeof logMethod>(ctx, logMethod, ({} as unknown) as Logger, args, logFn, 5);

span.end();

const { spanId, traceId } = span.context();
const [obj, ...rest] = args;
expect(logFn).toHaveBeenLastCalledWith({ spanId, traceId, ...obj }, ...rest);
});
});
8 changes: 0 additions & 8 deletions tests/tracing/tracing.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,6 @@ describe('tracing', function () {
await expect(tracing.stop()).resolves.toBeUndefined();
});

it('should return an error if url is not configured', function () {
process.env.TELEMETRY_TRACING_ENABLED = 'true';

const action = () => new Tracing('test');

expect(action).toThrow('env-var: "TELEMETRY_TRACING_URL" is a required variable, but it was not set');
});

it('should return a tracer if everything is configured', async function () {
process.env.TELEMETRY_TRACING_ENABLED = 'true';
process.env.TELEMETRY_TRACING_URL = 'http://localhost:55681/v1/trace';
Expand Down

0 comments on commit 688d67f

Please sign in to comment.