/** * Demo: Child loggers for request-scoped context * * Shows how to use child loggers to add persistent context * like requestId, userId, etc. * * Run: npx tsx examples/child-loggers.ts */ import { createLogger, createConsoleTransport } from '../src/index.js' const logger = createLogger({ name: 'demo-child', level: 'debug', transports: [createConsoleTransport({ pretty: true, level: 'debug' })], }) console.log('\n=== Base Logger ===\n') logger.info('Base logger - no extra context') logger.debug({ action: 'startup' }, 'Application starting') console.log('\n=== Request-Scoped Child Logger ===\n') // Simulate an incoming request function handleRequest(requestId: string, userId: number) { // Create child logger with request context const reqLogger = logger.child({ requestId, userId }) reqLogger.info('Request started') reqLogger.debug({ path: '/api/users' }, 'Processing request') reqLogger.info({ responseTime: 45 }, 'Request completed') } handleRequest('req-abc123', 42) handleRequest('req-def456', 99) console.log('\n=== Nested Child Loggers ===\n') // Child of a child - context accumulates const serviceLogger = logger.child({ service: 'payments' }) const txLogger = serviceLogger.child({ transactionId: 'tx-789' }) serviceLogger.info('Payment service initialized') txLogger.info({ amount: 99.99, currency: 'USD' }, 'Processing payment') txLogger.warn({ retry: 1 }, 'Payment gateway timeout, retrying') txLogger.info('Payment completed') console.log('\n=== Base Logger Still Clean ===\n') logger.info('Base logger unchanged - no child context here')