Context

Logging context is a set of key-value fields that are automatically added to every log entry. This is useful for correlating events across a request, job, or task.

Context APIs

log_context()

A context manager for temporary context. Values are applied inside the with block and removed on exit.

with bozo.log_context(request_id="req-123", user_id=42):
    log.info("processing")

set_context()

Sets persistent context values for the current thread/async task. Values remain until cleared.

bozo.set_context(service="api", version="1.0")
log.info("started")

clear_context()

Clears context values. Pass keys to remove specific fields, or call without arguments to clear all.

bozo.clear_context("request_id")
bozo.clear_context()

Thread and async safety

Context is scoped per thread and async task. This means:

  • Context does not leak across threads.
  • Concurrent async tasks keep independent context.

Practical examples

Web request handling

def handle_request(request):
    with bozo.log_context(
        request_id=request.id,
        method=request.method,
        path=request.path,
    ):
        log.info("request_start")
        # process request
        log.info("request_end")

Background tasks

def run_job(job):
    with bozo.log_context(job_id=job.id, queue=job.queue):
        log.info("job_started")
        # process job
        log.info("job_finished")

This site uses Just the Docs, a documentation theme for Jekyll.