Skip to content

Commit

Permalink
Add trace property to logs created via logger.write() (#1446)
Browse files Browse the repository at this point in the history
* Update index.ts

* Fix linter error.

* Lint

* Actually fix lint issues.

---------

Co-authored-by: Daniel Lee <[email protected]>
Co-authored-by: Daniel Lee <[email protected]>
  • Loading branch information
3 people authored Aug 26, 2024
1 parent b0b7eab commit 0878a8a
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions src/logger/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,13 @@ function removeCircular(obj: any, refs: any[] = []): any {
* @public
*/
export function write(entry: LogEntry) {
const ctx = traceContext.getStore();
if (ctx?.traceId) {
entry[
"logging.googleapis.com/trace"
] = `projects/${process.env.GCLOUD_PROJECT}/traces/${ctx.traceId}`;
}

UNPATCHED_CONSOLE[CONSOLE_SEVERITY[entry.severity]](JSON.stringify(removeCircular(entry)));
}

Expand Down Expand Up @@ -147,17 +154,13 @@ function entryFromArgs(severity: LogSeverity, args: any[]): LogEntry {
if (lastArg && typeof lastArg === "object" && lastArg.constructor === Object) {
entry = args.pop();
}
const ctx = traceContext.getStore();

// mimic `console.*` behavior, see https://nodejs.org/api/console.html#console_console_log_data_args
let message = format(...args);
if (severity === "ERROR" && !args.find((arg) => arg instanceof Error)) {
message = new Error(message).stack || message;
}
const out: LogEntry = {
"logging.googleapis.com/trace": ctx?.traceId
? `projects/${process.env.GCLOUD_PROJECT}/traces/${ctx.traceId}`
: undefined,
...entry,
severity,
};
Expand Down

0 comments on commit 0878a8a

Please sign in to comment.