Skip to content

Commit c290b14

Browse files
authored
Handle non-string logged content with trace ID injection (#186)
* Use util.inspect to get string repr for non-string log content * Add unit test to check that logging objects works as expected
1 parent 4f8e944 commit c290b14

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

src/trace/patch-console.spec.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,14 @@ describe("patchConsole", () => {
8282
cnsole.log();
8383
expect(log).toHaveBeenCalledWith("[dd.trace_id=123456 dd.span_id=78910]");
8484
});
85+
it("injects trace context into logged object message", () => {
86+
patchConsole(cnsole as any, contextService);
87+
88+
cnsole.log({ objectKey: "objectValue", otherObjectKey: "otherObjectValue" });
89+
expect(log).toHaveBeenCalledWith(
90+
"[dd.trace_id=123456 dd.span_id=78910] { objectKey: 'objectValue', otherObjectKey: 'otherObjectValue' }",
91+
);
92+
});
8593
it("leaves empty message unmodified when there is no trace context", () => {
8694
contextService.rootTraceContext = undefined;
8795
patchConsole(cnsole as any, contextService);

src/trace/patch-console.ts

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import * as shimmer from "shimmer";
2+
import { inspect } from "util";
23

34
import { getLogLevel, LogLevel, setLogLevel } from "../utils/log";
45
import { TraceContextService } from "./trace-context-service";
@@ -58,7 +59,14 @@ function patchMethod(mod: Console, method: LogMethod, contextService: TraceConte
5859
arguments.length = 1;
5960
arguments[0] = prefix;
6061
} else {
61-
arguments[0] = `${prefix} ${arguments[0]}`;
62+
let logContent = arguments[0];
63+
64+
// If what's being logged is not a string, use util.inspect to get a str representation
65+
if (typeof logContent !== "string") {
66+
logContent = inspect(logContent);
67+
}
68+
69+
arguments[0] = `${prefix} ${logContent}`;
6270
}
6371
}
6472
} catch (error) {

0 commit comments

Comments
 (0)