Structured Logging With Levels And Context
Emit structured JSON logs with levels context binding and sampling for production observability without blocking the event loop.
Code
export function createLogger({level='info',sample=1,context={}}={}){const LEVELS={debug:10,info:20,warn:30,error:40};const current=LEVELS[level];function log(lvl,msg,data={}){if(LEVELS[lvl]<current)return;if(Math.random()>sample)return;const entry={ts:new Date().toISOString(),level:lvl,msg,...context,...data};if(lvl==='error')process.stderr.write(JSON.stringify(entry)+'\n');else process.stdout.write(JSON.stringify(entry)+'\n');}const logger={debug:(m,d)=>log('debug',m,d),info:(m,d)=>log('info',m,d),warn:(m,d)=>log('warn',m,d),error:(m,d)=>log('error',m,d),child:(ctx)=>createLogger({level,sample,context:{...context,...ctx}})};return logger;}Report a problem with this exampleOpens a pre-filled issue on GitHub.