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:
const parentLog = new LogLayer({
transport: new ConsoleTransport({
logger: console
})
})
const childLog = parentLog.child()Inheritance Behavior
Child loggers inherit:
- Configuration from the parent
- Context data (as a shallow copy by default, or shared reference if configured)
- Plugins
- Groups (shared reference — runtime changes propagate)
Configuration Inheritance
All configuration options are inherited from the parent:
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:
- Copy the parent's context to the child logger at creation time
- Maintain independent context after creation
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"Group Inheritance
When groups are configured, child loggers share the parent's group configuration and active groups filter by reference. This means runtime changes (such as addGroup(), removeGroup(), setGroupLevel(), or setActiveGroups()) on either parent or child affect both:
const parentLog = new LogLayer({
transport: [
new ConsoleTransport({ id: 'console', logger: console }),
new DatadogTransport({ id: 'datadog', logger: datadog }),
],
groups: {
database: { transports: ['datadog'], level: 'error' },
},
})
const childLog = parentLog.child()
// Parent changes the group level — child sees it too
parentLog.setGroupLevel('database', 'debug')
childLog.withGroup('database').debug('query ran') // sent (debug >= debug)However, persistent group tags (assigned via withGroup() on an instance) are copied independently. A child created with withGroup() does not affect the parent's tags:
const dbLogger = parentLog.withGroup('database')
dbLogger.error('Pool exhausted') // tagged with 'database'
parentLog.error('Something else') // not tagged with any group