Skip to main content

Pure-Python semantic logging library with context-local values.

Project description

contextuallogging

Stable Version Build Status Documentation Status Checked with mypy Linting: Ruff

Pure-Python semantic logging library with context-local values.

Source
Documentation

Basic Usage

This packages introduces two primary components:

  1. The ContextualFormatter logging formatter subclass.
  2. The @context decorator.

This is a basic example:

import sys
import logging
from contextuallogging import context, ContextualFormatter

logger = logging.getLogger()
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(ContextualFormatter())
logger.addHandler(handler)
logger.setLevel(logging.INFO)

@context(keyword="username", key="user")
def inner_function(username: str) -> None:
    logger.info("inner_function")

@context(keyword="request_id")
def outer_function(request_id: str) -> None:
    logger.info("outer_function")
    inner_function(username="cfandrews")
    logger.info("outer_function again")

outer_function(request_id="7fb9b341")

Which will output:

{"level": "INFO", "logger": "root", "message": "outer_function", "request_id": "7fb9b341", "timestamp": "2023-11-25T20:56:41.796564Z"}
{"level": "INFO", "logger": "root", "message": "inner_function", "request_id": "7fb9b341", "timestamp": "2023-11-25T20:56:41.797024Z", "user": "cfandrews"}
{"level": "INFO", "logger": "root", "message": "outer_function again", "request_id": "7fb9b341", "timestamp": "2023-11-25T20:56:41.797075Z"}

ContextualFormatter

The ContextualFormatter is a subclass of logging.Formatter and can be used in the exact same way as any other logging formatter. This class formats log messages as JSON blobs and includes a number of fields by default, such as an ISO 8601 timestamp in the UTC timezone, log level, logger name, and message. Logging context is added to the output JSON blob as additional fields mixed into the base log.

@context

The @context decorator adds fields to the logging context from the keyword arguments passed into the wrapped function. The logging context persists for the entire function call and is automatically reset after the function returns, creating a stack-like structure in which context is persisted down the call stack but not back up.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

contextuallogging-1.0.2.tar.gz (9.2 kB view hashes)

Uploaded Source

Built Distribution

contextuallogging-1.0.2-py3-none-any.whl (8.6 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page