Structured Logging
Log bukan hanya console.log("error happened"). Structured logging menggunakan format terstruktur (JSON) sehingga bisa di-query, di-filter, dan di-analisis.
Unstructured vs Structured
// ❌ Unstructured — susah di-parse
console.log("User 123 failed login from 192.168.1.1");
// ✅ Structured — mudah di-query
logger.warn("Login failed", {
userId: 123,
ip: "192.168.1.1",
reason: "invalid_password",
attemptCount: 3,
});
Log Levels
- TRACE — Detail internal (development only)
- DEBUG — Info untuk debugging
- INFO — Event penting (user signup, order created)
- WARN — Potentially problematic (retry, slow query)
- ERROR — Error yang perlu perhatian
- FATAL — Aplikasi tidak bisa lanjut
Best Practices
// 1. Selalu tambahkan context
logger.info("Order created", {
orderId: order.id,
userId: user.id,
total: order.total,
items: order.items.length,
});
// 2. Gunakan correlation ID untuk tracing
const correlationId = req.headers["x-correlation-id"] || uuid();
logger.info("Processing request", { correlationId, path: req.path });
// 3. Jangan log sensitive data
logger.info("User login", {
userId: user.id,
email: maskEmail(user.email), // u***@example.com
// JANGAN: password, token, credit card
});
Libraries
- Node.js — Pino (fastest), Winston (feature-rich)
- PHP — Monolog (Laravel default)
- Python — structlog, python-json-logger