구조화된 로그 기록 모범 사례
운영 문제를 더 쉽게 구문 분석하고 분석하며 신속하게 디버깅할 수 있도록 구조화된 로그 기록을 구현합니다.
구조화된 로그 기록 모범 사례은(는) CoddyKit의 무료 Production Debugging & Incident Response Playbook 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Production Debugging & Incident Response Playbook 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Production Debugging & Incident Response Playbook 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What are Logs?
Logs are records of events that happen in your application or system. Think of them as a diary for your software!
They're crucial for understanding what your program is doing, especially when things go wrong in a live "production" environment.
The Messy Truth
Often, logs are just plain text strings. This is called unstructured logging. While easy to write, unstructured logs are hard for computers to read and analyze, making debugging a slow, manual process.
Consider this example:
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def process_order(order_id, item_count):
logger.info(f"Processing order {order_id} with {item_count} items.")
if item_count > 10:
logger.warning(f"Large order detected for {order_id}. Items: {item_count}.")
logger.info(f"Order {order_id} processed successfully.")
if __name__ == "__main__":
process_order("ORD-123", 5)
process_order("ORD-456", 12)What is Structured Logging?
Structured logging means your logs are formatted as machine-readable data, not just free-form text. The most common format is JSON.
Instead of a single string, each log entry is an object with key-value pairs. This makes them easy to search, filter, and analyze programmatically.
Why Structured Logging Rocks
Structured logs offer many advantages:
- Faster Debugging: Quickly find relevant events.
- Better Analysis: Easily query and aggregate data.
- Automated Tools: Integrate with monitoring and alerting systems.
- Consistency: Ensures all logs contain expected fields.
JSON is King
While other formats exist, JSON (JavaScript Object Notation) is the most popular choice for structured logging due to its simplicity and widespread support.
A JSON log entry is a self-contained object, making it incredibly versatile for storing varied data. Here's what a structured log might look like:
{
"timestamp": "2023-10-27T10:30:00Z",
"level": "INFO",
"service": "order-processor",
"message": "Order processed successfully",
"order_id": "ORD-123",
"item_count": 5
}Code It Up!
Let's see how to implement structured logging. Many languages have libraries that make this easy. Here's a basic Python example using the standard logging module with a custom JSON formatter.
import logging
import json
class JsonFormatter(logging.Formatter):
def format(self, record):
log_entry = {
"timestamp": self.formatTime(record, self.datefmt),
"level": record.levelname,
"name": record.name,
"message": record.getMessage(),
"file": record.filename,
"line": record.lineno
}
if hasattr(record, 'order_id'):
log_entry['order_id'] = record.order_id
if hasattr(record, 'item_count'):
log_entry['item_count'] = record.item_count
return json.dumps(log_entry)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setFormatter(JsonFormatter())
logger.addHandler(handler)
def process_order(order_id, item_count):
extra_data = {'order_id': order_id, 'item_count': item_count}
logger.info("Processing order", extra=extra_data)
if item_count > 10:
logger.warning("Large order detected", extra=extra_data)
logger.info("Order processed successfully", extra=extra_data)
if __name__ == "__main__":
process_order("ORD-123", 5)
process_order("ORD-456", 12)Must-Have Fields
Every structured log entry should include these core fields for effective analysis:
timestamp: When the event happened (ISO 8601 format).level: Severity (INFO, WARN, ERROR, DEBUG).service: Which service or application generated the log.message: A human-readable summary of the event.hostname/pod_name: Where the log originated.
Enrich Your Logs
Beyond essential fields, add contextual data specific to the event. This is key for tracing requests across distributed systems, helping you connect the dots when debugging complex issues.
request_id: To track a single user request.user_id: To identify the user involved.transaction_id: For specific business transactions.
import logging
import json
import uuid
# Reusing the JsonFormatter from previous scene
class JsonFormatter(logging.Formatter):
def format(self, record):
log_entry = {
"timestamp": self.formatTime(record, self.datefmt),
"level": record.levelname,
"message": record.getMessage()
}
for key, value in record.__dict__.items():
if not key.startswith('_') and key not in ['name', 'levelname', 'pathname', 'filename', 'module', 'exc_info', 'exc_text', 'stack_info', 'lineno', 'funcName', 'created', 'msecs', 'relativeCreated', 'thread', 'threadName', 'processName', 'process', 'args', 'msg', 'asctime']:
log_entry[key] = value
return json.dumps(log_entry)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setFormatter(JsonFormatter())
logger.addHandler(handler)
def handle_web_request(user_id):
request_id = str(uuid.uuid4())[:8]
extra_data = {'request_id': request_id, 'user_id': user_id, 'service': 'api-gateway'}
logger.info("Received web request", extra=extra_data)
if user_id == "user-vip":
logger.info("VIP user request detected", extra=extra_data)
else:
logger.debug("Standard user request", extra=extra_data)
logger.info("Request processed", extra=extra_data)
if __name__ == "__main__":
handle_web_request("user-123")
handle_web_request("user-vip")Log Levels
Log levels help categorize the severity and importance of a log message. Common levels include:
- DEBUG: Detailed info, only useful when diagnosing problems.
- INFO: Confirmation that things are working as expected.
- WARN: An unexpected event, but the application is still running.
- ERROR: An error that prevents some functionality from working.
- CRITICAL: A severe error, application might be unable to continue.
Quick Check
Structured logging is a powerful technique for improving observability. Let's test your understanding of its key advantages.
Structured Logging Recap
You've learned about the power of structured logging! By formatting your logs as machine-readable data (like JSON), you unlock faster debugging, better analysis, and seamless integration with monitoring tools.
Remember to include essential fields and contextual data to make your logs truly useful for diagnosing issues in production.
자주 묻는 질문
“구조화된 로그 기록 모범 사례” 강의는 무료인가요?
네 — “구조화된 로그 기록 모범 사례” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Production Debugging & Incident Response Playbook 강의 전체를 잠금 해제할 수 있습니다. Production Debugging & Incident Response Playbook 강의에는 총 4개의 강의가 포함되어 있습니다.
“구조화된 로그 기록 모범 사례”에서 뭘 배우나요?
운영 문제를 더 쉽게 구문 분석하고 분석하며 신속하게 디버깅할 수 있도록 구조화된 로그 기록을 구현합니다. 브라우저에서 직접 실행하는 실습 코드로 Production Debugging & Incident Response Playbook을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Production Debugging & Incident Response Playbook을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Production Debugging & Incident Response Playbook은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“구조화된 로그 기록 모범 사례” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Production Debugging & Incident Response Playbook 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Production Debugging & Incident Response Playbook 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 구조화된 로그 기록 모범 사례
- 메트릭, 대시보드, 관측 가능성
- 스마트한 경고 전략 설계
- 로그 집계 및 보존 전략