Structured Logging Patterns — DevOps

Structured Logging Log bukan hanya console.log("error happened"). Structured logging menggunakan format terstruktur (JSON) sehingga bisa di-query, di-filter, da

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

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