Structured logging utility for Node.js
Quick Answer
A structured JSON logger writes machine-parseable log objects with a timestamp and level — making logs instantly queryable in Datadog, CloudWatch, or any log aggregation platform.
1type LogLevel = 'info' | 'warn' | 'error' | 'debug';
2
3const logger = {
4 log: (level: LogLevel, message: string, meta?: any) => {
5 const timestamp = new Date().toISOString();
6 const log = { timestamp, level, message, ...(meta && { meta }) };
7 console.log(JSON.stringify(log));
8 },
9
10 info: (message: string, meta?: any) => logger.log('info', message, meta),
11 warn: (message: string, meta?: any) => logger.log('warn', message, meta),
12 error: (message: string, meta?: any) => logger.log('error', message, meta),
13 debug: (message: string, meta?: any) => logger.log('debug', message, meta)
14};
15
16export default logger;Structured logging outputs JSON objects instead of plain strings, making logs machine-parseable by tools like Datadog, CloudWatch, and ELK. This logger provides the four standard levels — info, warn, error, debug — with automatic timestamps and optional metadata, with zero external dependencies.
For production, Pino is the recommended choice — it is extremely fast, has a rich plugin ecosystem, and supports log redaction. This snippet is ideal for simple scripts, lambdas, or projects where adding a dependency is undesirable.
This free typescript code snippet for simple logger is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this beginner-level example will help you implement simple logger quickly and correctly.
All snippets in the Snippetly library follow typescript best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses typescript.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.