Logging Best Practices
You'll learn how to structure production logs so they help you debug issues quickly while keeping sensitive information secure.
The Core Idea
Logging is your lifeline when debugging production issues, but poorly structured logs create noise or, worse, leak sensitive data. Well-crafted logs use appropriate severity levels, include helpful context, and sanitize sensitive information before it reaches your logging system.
Think of production logs like a flight data recorder: they need enough detail to reconstruct what happened during a crash, but they shouldn't record passengers' credit card conversations.
Log Levels Matter
Use severity levels correctly to filter what matters:
console.debug('User preferences loaded'); // Development detail
console.info('Payment initiated for order #1234'); // Normal operation
console.warn('API retry attempt 2/3'); // Potential issue
console.error('Payment gateway timeout', { orderId: 1234 }); // Critical failure
Add Context, Not Clutter
Include identifiers that help trace issues without overwhelming detail:
console.error('Checkout failed', {
orderId: 'ORD-5678',
step: 'payment-validation',
timestamp: Date.now(),
userAgent: navigator.userAgent
});
Sanitize Sensitive Data
Never log passwords, tokens, full credit card numbers, or PII:
// ❌ BAD
console.info('Login successful', { email, password });
// ✅ GOOD
console.info('Login successful', { userId: user.id });
Use Feature Flags for Testing to enable verbose logging temporarily without deploying new code, and pair this with Session Replay Tools to see what users experienced.
Key Takeaway: Structure production logs with appropriate severity levels, relevant context like IDs and timestamps, and always sanitize sensitive information—good logs help you debug without compromising security or creating noise.