Skip to content

Child Loggers

Child loggers allow you to create new logger instances that inherit configuration, context, and plugins from their parent logger. This is particularly useful for creating loggers with additional context for specific components or modules while maintaining the base configuration.

Creating Child Loggers

Use the child() method to create a child logger:

typescript
const parentLog = new LogLayer({
  transport: new ConsoleTransport({
    logger: console
  })
})

const childLog = parentLog.child()

Inheritance Behavior

Child loggers inherit:

  1. Configuration from the parent
  2. Context data (as a shallow copy by default, or shared reference if configured)
  3. Plugins

Configuration Inheritance

All configuration options are inherited from the parent:

typescript
const parentLog = new LogLayer({
  transport: new ConsoleTransport({
    logger: console
  }),
  contextFieldName: 'context',
  metadataFieldName: 'metadata',
  errorFieldName: 'error'
})

// Child inherits all configuration
const childLog = parentLog.child()

Context Inheritance

Context inheritance behavior depends on the Context Manager being used. By default, the Default Context Manager is used.

When creating child loggers, the Default Context Manager will:

  1. Copy the parent's context to the child logger at creation time
  2. Maintain independent context after creation
typescript
parentLogger.withContext({ requestId: "123" });

const childLogger = parentLogger.child();
// Child inherits parent's context at creation via shallow-copy
childLogger.info("Initial log"); // Includes requestId: "123"

// Child can modify its context independently
childLogger.withContext({ userId: "456" });
childLogger.info("User action"); // Includes requestId: "123" and userId: "456"

// Parent's context remains unchanged
parentLogger.info("Parent log"); // Only includes requestId: "123"