Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 80

Structured Logging for Monitoring

This lesson is built with resources from apxml.com and dash0.com.

Hello! Welcome to the sixth lesson in our final module, Deploying AI Models as Services.

In our previous lesson, you successfully deployed your containerized AI application to Google Cloud Run, making it a live, scalable web service. This was a major milestone, but a deployed service without visibility is a black box. When a user reports a problem or performance degrades, how do you investigate?

This lesson addresses that critical gap. Your learning outcome is to implement structured logging to capture requests, predictions, and errors for monitoring. We'll transform your application from a black box into an observable system by implementing production-grade logging. As a backend engineer, you're likely familiar with logging, and here we'll apply best practices specifically for an AI service, using a powerful library called structlog.

1. Why Structured Logging is Essential for AI Services

When your FastAPI service is running in the cloud, logs are your primary source of truth. They are essential for:

  • Debugging: Tracing errors back to specific requests and seeing the context in which they occurred.
  • Monitoring: Tracking request volume, response times, and error rates.
  • Auditing: Recording what predictions were made for given inputs.

Simply printing text to the console isn't enough in production. We need structured logs, typically in JSON format. These logs are not just for human eyes; they are designed to be ingested, parsed, and queried by automated monitoring systems.

The MLOps flowchart below highlights where logging fits into a production pipeline. Notice the "Input Data Log" and "Prediction Log"—these are critical for understanding and improving the model over time.

Classification Model Deployment with FastAPI and Docker Flowchart
This flowchart shows a typical MLOps pipeline. The 'Input Data Log' and 'Prediction Log' components are essential for monitoring the behavior and performance of the deployed model, which is what we will implement today.

2. From Basic Logging to structlog

Python's built-in logging module is functional, but creating rich, structured, and contextualized logs often requires significant boilerplate code. We will use structlog, a library that builds on top of the standard logging module to make structured logging clean and powerful.

structlog's philosophy is based on a processor pipeline. Every time you log a message, an event dictionary is created and passed through a series of functions (processors) that enrich it with information like a timestamp, the log level, and contextual data before a final "renderer" processor formats it as a string (e.g., a JSON string).

This approach is highly declarative and makes it easy to manage what your logs contain.

Leveling Up Your Python Logs with Structlog

To understand the philosophy behind structlog and why it's a step up from the standard library, let's read the introduction from the article 'Leveling Up Your Python Logs with Structlog'.

Read the section 'Understanding the Structlog philosophy'. This will give you a clear mental model of how structlog's processor pipeline works.


3. Implementing a Production-Ready Logging Configuration

Our goal is to create a configuration that outputs JSON logs in production. This involves setting up the correct processor chain. First, you'll need to install structlog:

pip install structlog

Now, let's create a new file in your project directory called log_config.py. This will centralize our logging setup.

# log_config.py

import logging
import sys
import os
import structlog

def configure_logging():
    """
    Configures logging for the application.
    In a production environment (indicated by APP_ENV=production), logs are formatted as JSON.
    Otherwise, logs are formatted for human-readability in the console.
    """
    log_level = logging.INFO
    is_production = os.environ.get("APP_ENV") == "production"

    # These processors are shared between development and production
    shared_processors = [
        structlog.contextvars.merge_contextvars,
        structlog.processors.add_log_level,
        structlog.processors.StackInfoRenderer(),
        structlog.dev.set_exc_info,
        structlog.processors.TimeStamper(fmt="iso", utc=True),
        structlog.processors.EventRenamer("message"), # Rename 'event' to 'message'
    ]

    if is_production:
        # Production-specific processors
        processors = shared_processors + [
            structlog.processors.dict_tracebacks,
            structlog.processors.JSONRenderer(),
        ]
        # In production, we don't need to configure the standard logger
        # because structlog will handle everything.
    else:
        # Development-specific processors
        processors = shared_processors + [
            structlog.dev.ConsoleRenderer(colors=True),
        ]
        # Configure standard logging to play nicely with structlog
        logging.basicConfig(
            format="%(message)s",
            stream=sys.stdout,
            level=log_level,
        )

    structlog.configure(
        processors=processors,
        wrapper_class=structlog.make_filtering_bound_logger(log_level),
        context_class=dict,
        logger_factory=structlog.PrintLoggerFactory(),
        cache_logger_on_first_use=is_production,
    )

    logger = structlog.get_logger()
    logger.info("Logging configured", is_production=is_production)

This configuration is powerful because it's environment-aware.

  • In development, it uses ConsoleRenderer for pretty, colored logs.
  • In production (APP_ENV=production), it switches to JSONRenderer and adds dict_tracebacks to structure exceptions.

Leveling Up Your Python Logs with Structlog

The configuration above is based on the best practices described in the structlog guide. Let's review the section that explains this production setup in more detail.

Read the section 'The production configuration: machine-readable JSON'. Focus on the reasons for choosing JSONRenderer, ISO 8601 timestamps, and dict_tracebacks. This will solidify your understanding of our log_config.py file.


4. Integrating Logging with FastAPI via Middleware

The single most important practice for effective logging in a web service is adding context. We need a way to group all log messages that belong to a single API request. The standard pattern is to assign a unique correlation ID (or request_id) to each incoming request.

FastAPI middleware is the perfect place to do this. The middleware will:

  1. Generate a unique request_id for each request.
  2. Bind the request_id and other request-level information (like client IP, path, method) to the logging context using structlog.contextvars.
  3. Log the start and end of the request, calculating the total duration.

Let's modify your main.py to incorporate the logging configuration and add the middleware.

# main.py

import time
import uuid
import os

from fastapi import FastAPI, Request, Depends, HTTPException, status
from fastapi.responses import StreamingResponse
from fastapi.security import APIKeyHeader

import structlog
from log_config import configure_logging # Import our new function

# --- Application Setup ---

# Call this at the start of your application
configure_logging()

# Get a logger instance
logger = structlog.get_logger()

# ... (rest of your imports and setup for LLM client)

# --- Middleware for Contextual Logging ---

@app.middleware("http")
async def logging_middleware(request: Request, call_next):
    # Clear any existing context from previous requests
    structlog.contextvars.clear_contextvars()

    # Generate a unique request ID
    request_id = request.headers.get("X-Request-ID", str(uuid.uuid4()))
    
    # Bind request-specific context
    structlog.contextvars.bind_contextvars(
        request_id=request_id,
        client_ip=request.client.host,
        http_method=request.method,
        http_path=request.url.path,
    )

    start_time = time.monotonic()
    logger.info("Request started")

    try:
        response = await call_next(request)
        duration_ms = (time.monotonic() - start_time) * 1000
        
        # Add response context
        structlog.contextvars.bind_contextvars(
            http_status_code=response.status_code,
            duration_ms=round(duration_ms, 2),
        )

        log_level = "info"
        if 500 <= response.status_code < 600:
            log_level = "error"
        elif 400 <= response.status_code < 500:
            log_level = "warning"
        
        getattr(logger, log_level)("Request finished")
        
    except Exception as e:
        duration_ms = (time.monotonic() - start_time) * 1000
        structlog.contextvars.bind_contextvars(
            http_status_code=500,
            duration_ms=round(duration_ms, 2)
        )
        logger.exception("Unhandled exception during request")
        raise e # Re-raise the exception to let FastAPI handle it

    return response

# --- Security and Endpoints ---

# ... (your existing APIKeyHeader and get_api_key function)

# Update get_api_key to include logging
async def get_api_key(api_key: str = Depends(api_key_header)):
    if api_key == os.environ.get("API_KEY"):
        logger.debug("API key authentication successful")
        return api_key
    else:
        logger.warning("API key authentication failed", provided_key=api_key)
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid API Key",
        )

# ... (your existing /query-stream endpoint)

# Update the endpoint to log key events
@app.post("/query-stream/")
async def query_stream(query: str, api_key: str = Depends(get_api_key)):
    logger.info("Received query for streaming response", query=query)
    try:
        # ... (your existing code to get streaming response from LLM)
        return StreamingResponse(llm_client.stream(query), media_type="text/event-stream")
    except Exception as e:
        logger.exception(
            "An error occurred while processing the streaming query",
            query=query
        )
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="An internal error occurred."
        )

This code snippet is a complete, production-ready example of contextual logging in a FastAPI application. The logging_middleware automatically enriches every log call made during a request's lifecycle.

Leveling Up Your Python Logs with Structlog

The middleware pattern we've implemented is a standard for adding request-scoped context. The structlog guide provides an excellent example and explanation that closely mirrors our implementation.

Read the sections 'Mastering contextual logging' and 'Reliable context propagation in web apps'. Pay special attention to the FastAPI middleware example. This will reinforce why contextvars are so powerful in a concurrent environment like an API server.

Test your understanding!

Imagine you want to track which model version is being used for each prediction. How would you modify the logging configuration and your application code to add a model_version field (e.g., "gpt2-large-v1.2") to every single log message generated by the application?

Show answer

There are two great ways to do this, but the best is using a custom processor for global context.

In log_config.py, you would add a simple processor that injects the version into the event dictionary. This is efficient because the value is static.

# In log_config.py

def add_global_context(logger, method_name, event_dict):
    event_dict["model_version"] = "gpt2-large-v1.2" # Or read from env var
    return event_dict

# ... then add it to your shared_processors list, near the beginning
shared_processors = [
    add_global_context, # Add the new processor here
    structlog.contextvars.merge_contextvars,
    # ...
]

This ensures model_version is present in every log record automatically, without needing to bind it for every request.


5. Final Steps and Seeing it in Action

  1. Update requirements.txt: Add structlog to your requirements.txt file.
  2. Update Dockerfile: Add ENV APP_ENV=production. This tells our application running inside the container to use the JSON logging format.
    # ... after the WORKDIR instruction
    ENV APP_ENV=production
    # ...
    
  3. Rebuild and Rerun: Rebuild your Docker image and run it locally.
    docker build -t ai-streaming-api:latest .
    docker run -p 8000:8000 --env-file .env ai-streaming-api:latest
    
  4. Test: Make a request to your API using curl. You will now see structured JSON logs printed to your console, each containing the request_id and other context.

Here is an example of what a log line for a finished request might look like:

{
  "request_id": "c4a3f2b1-1d5f-4a6e-8b9c-0e2f1a3b4c5d",
  "client_ip": "127.0.0.1",
  "http_method": "POST",
  "http_path": "/query-stream/",
  "http_status_code": 200,
  "duration_ms": 1543.21,
  "level": "info",
  "timestamp": "2023-10-27T10:30:00.123456Z",
  "message": "Request finished"
}

If an error occurs, structlog will capture it beautifully.

Leveling Up Your Python Logs with Structlog

The dict_tracebacks processor is what turns a messy Python stack trace into a clean, queryable JSON object. Let's see an example of this.

Briefly review the section 'Capturing Python errors and exceptions' to see how logger.exception() and the dict_tracebacks processor work together to create structured error logs.


Conclusion

Congratulations! You have instrumented your AI service with production-grade structured logging. Your application is no longer a black box. The JSON logs it produces are rich with context and ready to be fed into a monitoring system.

Key Takeaways:

  • Structured Logging is Key: JSON logs are essential for automated parsing, searching, and alerting in production environments.
  • structlog Provides Power and Clarity: Its processor pipeline and context-aware features make it an excellent choice for building robust logging.
  • Middleware is for Context: FastAPI middleware is the ideal place to inject request-scoped context, such as a request_id, ensuring traceability.
  • Log What Matters: We are now capturing the full request lifecycle, including metadata, query content, performance timing, and structured exceptions.

What's Next?
Generating these detailed logs is the first half of the observability story. In our final lesson of the course, we will complete the picture by learning how to set up a monitoring dashboard to visualize key health and performance metrics. You'll see firsthand how the structured logs you've just implemented can be turned into powerful, actionable insights.

Structured Logging and Error Monitoring Dashboard
An example of a log monitoring dashboard that can be built using structured logs. This is what we will work towards in the next lesson.