Skip to content

Distributed Logging — Logging Across Microservice Boundaries

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you'll learn about Distributed Logging. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

Distributed logging correlates log entries across multiple services to reconstruct end-to-end request flows.

// Distributed log context propagation
class DistributedLogContext {
  constructor() {
    this.context = new AsyncLocalStorage();
  }

  extractFromRequest(req) {
    return {
      traceId: req.headers['x-trace-id'] || uuidv4(),
      parentSpanId: req.headers['x-span-id'],
      correlationId: req.headers['x-correlation-id'] || uuidv4(),
      clientId: req.headers['x-client-id']
    };
  }

  injectIntoRequest(context, reqOptions) {
    reqOptions.headers = {
      ...reqOptions.headers,
      'x-trace-id': context.traceId,
      'x-span-id': context.spanId,
      'x-correlation-id': context.correlationId
    };
    return reqOptions;
  }

  createChildSpan(context, operation) {
    return {
      traceId: context.traceId,
      parentSpanId: context.spanId,
      spanId: uuidv4(),
      operation,
      startTime: Date.now()
    };
  }

  logWithDistributedContext(entry) {
    const ctx = this.context.getStore();
    if (!ctx) return entry;

    return {
      ...entry,
      traceId: ctx.traceId,
      spanId: ctx.spanId,
      parentSpanId: ctx.parentSpanId,
      service: config.serviceName,
      instance: os.hostname()
    };
  }
}

// Service mesh integration (Istio)
// Envoy automatically adds:
// x-request-id, x-b3-traceid, x-b3-spanid, x-b3-parentspanid

// Cross-service log correlation
async function handleRequest(req, res) {
  const logCtx = new DistributedLogContext();
  const context = logCtx.extractFromRequest(req);

  // Call downstream service with context
  const downstreamReq = {
    url: 'http://scan-service.internal/scan',
    method: 'POST',
    data: req.body
  };

  logCtx.injectIntoRequest(context, downstreamReq);

  const response = await axios(downstreamReq);

  logger.info({
    message: 'Request processed across services',
    traceId: context.traceId,
    correlationId: context.correlationId,
    downstreamStatus: response.status,
    duration: Date.now() - req.startTime
  });
}

Distributed logging provides end-to-end visibility across service boundaries for complex microservice architectures.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro