Configure Application Logging
Logging helps developers understand application behavior and diagnose production failures.
Avoid relying exclusively on console.log() for production applications.
A structured logger should provide:
- Log levels.
- Timestamps.
- Request identifiers.
- Error context.
- JSON output.
- Configurable log destinations.
Common log levels include:
- debug.
- info.
- warn.
- error.
Never log passwords, access tokens, authorization headers, or sensitive personal information.
Basic Structured Logging
export const logger = {
info(message, metadata = {}) {
console.log(JSON.stringify({
level: 'info',
message,
timestamp: new Date().toISOString(),
...metadata
}));
},
error(message, metadata = {}) {
console.error(JSON.stringify({
level: 'error',
message,
timestamp: new Date().toISOString(),
...metadata
}));
}
};Creates a minimal JSON logger. For production applications, use a dedicated logging library with appropriate serialization and redaction.
Key Takeaways
Structured logs simplify troubleshooting.
Use appropriate log levels.
Never log authentication secrets.