Implement structured logging with JSON formats, log levels (DEBUG, INFO, WARN, ERROR), contextual logging, PII handling, and centralized logging. Use for logging, observability, log levels, structured logs, or debugging.
Comprehensive guide to implementing structured, secure, and performant logging across applications. Covers log levels, structured logging formats, contextual information, PII protection, and centralized logging systems.
Minimal working example:
// logger.ts
enum LogLevel {
DEBUG = 0, // Detailed information for debugging
INFO = 1, // General informational messages
WARN = 2, // Warning messages, potentially harmful
ERROR = 3, // Error messages, application can continue
FATAL = 4, // Critical errors, application must stop
}
class Logger {
constructor(private minLevel: LogLevel = LogLevel.INFO) {}
debug(message: string, context?: object) {
if (this.minLevel <= LogLevel.DEBUG) {
this.log(LogLevel.DEBUG, message, context);
}
}
info(message: string, context?: object) {
if (this.minLevel <= LogLevel.INFO) {
this.log(LogLevel.INFO, message, context);
}
}
warn(message: string, context?: object) {
// ... (see reference guides for full implementation)
Detailed implementations in the references/ directory:
| Guide | Contents |
|---|---|
| Log Levels | Log Levels |
| Structured Logging (JSON) | Structured Logging (JSON) |
| Contextual Logging | Contextual Logging |
| PII and Sensitive Data Handling | PII and Sensitive Data Handling |
| Performance Logging | Performance Logging |
| Centralized Logging | Centralized Logging |
| Distributed Tracing | Distributed Tracing |
| Log Sampling (High-Volume Services) | Log Sampling (High-Volume Services) |