Structured Logging Setup
Logging Library Comparison
Recommendation: Use
structlog for production LLM applications. It produces JSON by default, integrates with OpenTelemetry, and supports context binding (attach trace_id, user_id once and they appear on every log line). Use loguru if you prioritize developer experience during development.
Using structlog
Why structured logging instead ofprint() or basic logging? Because structured logs (JSON format) are machine-parseable. You can query them with tools like jq, feed them into Elasticsearch, or aggregate them in Grafana. A log line like {"event": "llm_request", "model": "gpt-4o", "latency_ms": 2300, "tokens": 1847} is infinitely more useful than INFO: Called GPT-4o in 2.3 seconds.
Custom LLM Logger
Request Tracing
Request tracing answers the question: “this user got a bad response — what happened?” In a typical LLM application, a single user request might trigger a retrieval query, two LLM calls (one for query expansion, one for generation), and a tool call. Without tracing, these are five disconnected log entries. With tracing, they are linked by a single trace ID, so you can reconstruct the full journey from user question to final answer. Think of tracing like a receipt at a restaurant: it links the order, the kitchen prep, the plating, and the delivery into one traceable transaction.Audit Logging
Audit logging serves a different purpose than operational logging. Operational logs help you debug; audit logs help you prove compliance. If your LLM application handles medical records, financial data, or personal information, regulators may require you to demonstrate who accessed what data, when, and what the system did with it. Audit logs are append-only (never modified or deleted), tamper-evident (content-hashed), and retained for a defined period. Even if you are not in a regulated industry today, audit logging is cheap insurance. When a customer asks “what did your AI do with my data?”, you want an answer.Debug Mode
Debug mode is your “X-ray vision” during development. It prints full prompts, responses, latency, and token counts for every LLM call. The key design principle: it is controlled entirely by environment variables, so you never need to change code to toggle it on or off. SetLLM_DEBUG=true in your .env during development, and remove it in production. No code changes, no risk of accidentally shipping debug logging.
Error Diagnostics
When an LLM API call fails, the error message is often cryptic: “Error code: 429” or “context_length_exceeded.” The diagnostics system below pattern-matches error messages to known failure modes and provides actionable suggestions. This is especially valuable for on-call engineers who may not be deeply familiar with LLM-specific failure patterns — instead of Googling the error, they get immediate guidance.Log Analysis
Raw logs are useless without analysis. The analyzer below turns your log files into actionable insights: which models are most expensive, where the latency bottlenecks are, and what errors are most common. Run this daily or weekly to catch trends before they become incidents. A gradual increase in P95 latency, for example, might indicate that your prompts are getting longer over time as conversation history grows unbounded.Logging Levels
What to Log vs. What Not to Log
This is where most teams get it wrong — they either log too little (cannot debug) or too much (PII exposure, storage costs, GDPR violations).
Edge case — multi-tenant logging: If your LLM application serves multiple customers, ensure tenant isolation in your logs. A log query for Customer A should never surface Customer B’s data. Use tenant-scoped log indexes or strict filtering. This is not just a privacy concern — it is a contractual obligation in most B2B agreements.
Edge case — PII in LLM responses: Even if you do not log user prompts, the model’s response might contain PII that the user provided in the prompt. If you log responses for quality review, run a PII detection pass (regex for emails/phones/SSNs, or a lightweight NER model) and redact before storage.
What is Next
API Design for AI
Learn to design robust APIs for LLM applications