Provide Business Insights: Logged events (e.g., "purchase_completed") can be analyzed to understand user behavior.
If you spend more than a few minutes searching for a problem in your logs, it's time to invest in these practices.
Quick Example
Here’s a before-and-after comparison of logging an error in an API endpoint:
Before (Unstructured, No Context):
logger.error("Failed to process order")
This tells you a failure occurred, but nothing more. Which order? Why? For whom?
After (Structured & Contextual):
logger.error(
"Order processing failure",
extra={
"event": "order_processing_failed",
"order_id": order.id,
"user_id": user.id,
"error": str(exception),
"payment_gateway_tx_id": transaction_id,
"correlation_id": request.correlation_id
}
)
This single entry provides all the forensic data needed to diagnose the issue, find the user, and trace the request across the system.
Key Takeaway
Your logs are a primary diagnostic tool; treat them with the same care as your code by making them structured, contextual, and appropriately leveled so you can solve problems faster. For a definitive guide, review the Twelve-Factor App methodology’s section on logs.