Production Debugging & Incident Response Playbook · Lekcja

Najlepsze praktyki logowania strukturalnego

Wdróż logowanie strukturalne, aby ułatwić analizę i przetwarzanie logów oraz szybciej debugować problemy produkcyjne.

Lekcja 1 z 411 kroki

Najlepsze praktyki logowania strukturalnego to bezpłatna lekcja Production Debugging & Incident Response Playbook na CoddyKit. To lekcja 1 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Production Debugging & Incident Response Playbook, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Production Debugging & Incident Response Playbook zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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.

Bezpłatny start

Ucz się Production Debugging & Incident Response Playbook dzięki korepetycjom AI — za darmo

Pisz i uruchamiaj kod w przeglądarce, otrzymuj natychmiastową pomoc od korepetytora AI dostępnego 24/7 i kontynuuj naukę w sieci lub w aplikacji.

Kursy
12
Lekcje
48

Często zadawane pytania

Czy lekcja „Najlepsze praktyki logowania strukturalnego” jest bezpłatna?

Tak — pełny tekst „Najlepsze praktyki logowania strukturalnego” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Production Debugging & Incident Response Playbook, przejdź na CoddyKit PRO. Kurs Production Debugging & Incident Response Playbook zawiera 4 lekcji w sumie.

Co nauczysz się w „Najlepsze praktyki logowania strukturalnego”?

Wdróż logowanie strukturalne, aby ułatwić analizę i przetwarzanie logów oraz szybciej debugować problemy produkcyjne. Ćwiczysz Production Debugging & Incident Response Playbook z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Production Debugging & Incident Response Playbook?

Nie wymagamy żadnego doświadczenia. Production Debugging & Incident Response Playbook w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 1 z 4.

Ile czasu zajmuje lekcja „Najlepsze praktyki logowania strukturalnego”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Production Debugging & Incident Response Playbook?

Tak. Każda lekcja Production Debugging & Incident Response Playbook zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Najlepsze praktyki logowania strukturalnego
  2. Metryki, pulpity i obserwowalność
  3. Projektowanie inteligentnych strategii alertowania
  4. Agregowanie logów i strategie ich przechowywania
← Powrót do Production Debugging & Incident Response Playbook