πŸ”§ DevOps

Logging

Logging

Recording application events. Essential for debugging and monitoring. ELK stack.

πŸ“– Detailed Explanation

Logging is the practice of recording, in chronological order, the events, states, and errors that occur while an application is running. Logs are an essential data source for debugging, monitoring, security auditing, and performance analysis. A well-designed logging system lets you quickly identify the cause when a failure occurs.

Log levels are generally divided into DEBUG, INFO, WARN, ERROR, and FATAL. In development environments, logs are recorded in detail down to the DEBUG level, while in production only INFO and above are recorded to manage log volume. Log levels should be changeable at runtime through environment variables so that DEBUG logs can be temporarily enabled during a failure.

Structured Logging records logs in a format such as JSON to make searching and analysis easier. JSON logs ({"event": "login", "userId": 123, "ip": "1.2.3.4"}) are easier to filter and aggregate in log analysis tools than plain text logs ("User 123 logged in").

Centralized log management is essential in modern microservices. Logs from each service are collected into systems such as the ELK stack (Elasticsearch, Logstash, Kibana), Loki+Grafana, Datadog, or Splunk, so they can be searched in one place and visualized with dashboards. In distributed systems, a trace ID is included in logs to trace the request flow.

πŸ’» Code Example

# Python κ΅¬μ‘°ν™”λœ λ‘œκΉ… μ„€μ • (structlog)
import structlog
import logging

# κ΅¬μ‘°ν™”λœ 둜거 μ„€μ •
structlog.configure(
    processors=[
        structlog.stdlib.filter_by_level,
        structlog.stdlib.add_logger_name,
        structlog.stdlib.add_log_level,
        structlog.processors.TimeStamper(fmt="iso"),
        structlog.processors.StackInfoRenderer(),
        structlog.processors.format_exc_info,
        structlog.processors.UnicodeDecoder(),
        # JSON 좜λ ₯ (ν”„λ‘œλ•μ…˜)
        structlog.processors.JSONRenderer()
    ],
    wrapper_class=structlog.stdlib.BoundLogger,
    context_class=dict,
    logger_factory=structlog.stdlib.LoggerFactory(),
    cache_logger_on_first_use=True,
)

log = structlog.get_logger()

# μ»¨ν…μŠ€νŠΈμ™€ ν•¨κ»˜ λ‘œκΉ…
def process_order(order_id: str, user_id: str):
    # μš”μ²­λ³„ μ»¨ν…μŠ€νŠΈ 바인딩
    log_ctx = log.bind(
        order_id=order_id,
        user_id=user_id,
        trace_id=get_trace_id()  # λΆ„μ‚° 좔적 ID
    )

    log_ctx.info("order_processing_started")

    try:
        result = payment_service.charge(order_id)
        log_ctx.info(
            "payment_completed",
            amount=result.amount,
            currency=result.currency
        )
    except PaymentError as e:
        log_ctx.error(
            "payment_failed",
            error_code=e.code,
            error_message=str(e)
        )
        raise
// κ΅¬μ‘°ν™”λœ 둜그 좜λ ₯ μ˜ˆμ‹œ (JSON Lines)
{"timestamp": "2024-01-15T09:30:00.123Z", "level": "info", "event": "order_processing_started", "order_id": "ORD-12345", "user_id": "USR-789", "trace_id": "abc123", "service": "order-api"}
{"timestamp": "2024-01-15T09:30:00.456Z", "level": "info", "event": "payment_completed", "order_id": "ORD-12345", "user_id": "USR-789", "trace_id": "abc123", "amount": 59900, "currency": "KRW"}
{"timestamp": "2024-01-15T09:30:01.789Z", "level": "error", "event": "payment_failed", "order_id": "ORD-12346", "user_id": "USR-790", "trace_id": "def456", "error_code": "INSUFFICIENT_FUNDS", "error_message": "Card declined"}

// Node.js κ΅¬μ‘°ν™”λœ λ‘œκΉ… (Pino)
const pino = require('pino');
const logger = pino({
  level: process.env.LOG_LEVEL || 'info',
  formatters: {
    level: (label) => ({ level: label })
  },
  timestamp: pino.stdTimeFunctions.isoTime
});

// μžμ‹ 둜거둜 μ»¨ν…μŠ€νŠΈ μΆ”κ°€
const reqLogger = logger.child({
  requestId: req.id,
  userId: req.user?.id
});
reqLogger.info({ path: req.path }, 'request received');

πŸ—£οΈ How It's Said in Practice

DevOps: "The log storage cost is way too high. It seems like some service is leaving DEBUG-level logs in production..."

Developer: "DEBUG was turned on in the payment service. If we switch it to INFO, the log volume should drop by 80%."

Senior: "Also, please make sure masking is applied so that PII (personally identifiable information) doesn't end up in the logs. Things like emails and phone numbers."

Interviewer: "How did you trace failures in a distributed system?"

Candidate: "I generated a trace ID for every request and included it in the logs. When you search by trace ID in Kibana, you can see the logs from every service the request passed through, in chronological order. Later I switched to OpenTelemetry and unified tracing and logging."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

Reviewer: "Please use a logger instead of `console.log(error)` in the catch block. Also, if you log the whole error object, the stack trace becomes searchable too."

Author: "I'll change it to something like `logger.error({ err, orderId }, 'Failed to process order')`."

⚠️ Cautions

πŸ“š Learn More