Structured Logging With Levels And Context

Emit structured JSON logs with levels context binding and sampling for production observability without blocking the event loop.

JavascriptCli Tooling

Code

javascriptsnippet
1 line
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;}

How it works

Structured Logging With Levels And Context keeps everything in the functions createLogger and log.

Points of care

  • The guard LEVELS[lvl]<current short-circuits the flow with an early return when its condition holds.

Using it

Entry signature: export function createLogger({level='info',sample=1,context={}}={})

The surface worth importing is createLogger; the helpers around it are private to the snippet.

Interactive Tools for This Topic

FAQ

Will the snippet run without installing packages?
Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `createLogger`, `log` at load time.