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;}How it works
Structured Logging With Levels And Context keeps everything in the functions createLogger and log.
Points of care
- The guard
LEVELS[lvl]<currentshort-circuits the flow with an earlyreturnwhen 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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.