Logging
Good logs help you understand what your app did, especially after something goes wrong.
In this page:
Syntax
console.error(message);
console.warn(message);
console.info(message);
console.debug(message);
Logging
Use log levels (error, warn, info, debug), include timestamps and context, and prefer structured JSON logs that tools can search. Libraries such as pino and winston handle levels and formats. Never log passwords or tokens.
Note:
Write logs to stdout and let the platform collect them.
Example: Logging
function log(level, msg, extra = {}) {
console.log(JSON.stringify({ level, msg, ...extra, ts: "2024-01-01T00:00:00.000Z" }));
}
log("info", "server started", { port: 3000 });
log("error", "db connection failed", { attempt: 2 });
// Output:
// {"level":"info","msg":"server started","port":3000,"ts":"2024-01-01T00:00:00.000Z"}
// {"level":"error","msg":"db connection failed","attempt":2,"ts":"2024-01-01T00:00:00.000Z"}
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Logging secrets
- Using console.log for everything
- Unstructured messages that cannot be searched
Chapter Summary
- Use log levels
- Structured JSON logs
- Include context and timestamps
- Never log secrets
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: