Ensuring Consistent Trace ID in Logs for Synchronous and Asynchronous Operations with google-cloud/logging-bunyan in Node.js

I’m using the google-cloud/logging-bunyan library in my Node.js application to log messages, and I want to ensure that all logs associated with a specific API call have the same trace ID, regardless of whether the operations are synchronous or asynchronous. However, I’m facing challenges ensuring consistent trace IDs in all logs.

Logger Configuration:

const { LoggingBunyan } = require('@google-cloud/logging-bunyan');
const createLogger = require("./CorrelateLogsHelper");

const loggingBunyan = new LoggingBunyan();
let loggerOption;

loggerOption = {
    name: 'rtmls-logs',
    level: 'info',
    streams: [loggingBunyan.stream('info')]
};

const { loggerContextMiddleware, log } = createLogger(process.env.GOOGLE_CLOUD_PROJECT, loggerOption);

Logs:

// Import log.
const { log } = require('./ls/Util/logging');

// Info Log.
log.info('[save] Non queueable message');

// Error Log.
log.error('[save] Error in saveOverflowedMessage: ', error);

I’m noticing inconsistencies in trace IDs in logs, especially for asynchronous operations and message queue worker operations. What additional steps or best practices should I follow to ensure a consistent trace ID across all logs associated with a particular API call?

Leave a Comment