Pure-Python semantic logging library with context-local values.
Project description
contextuallogging
Pure-Python semantic logging library with context-local values.
Basic Usage
This packages introduces two primary components:
- The
ContextualFormatter
logging formatter subclass. - 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
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for contextuallogging-1.0.2-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | dd840865a072d4e4d1dcddd238f98a9bf348be9329bc53b1faaca9f4ab6695f6 |
|
MD5 | 4ccaa7a7d92608bd48375c36642b4eec |
|
BLAKE2b-256 | 881fcda3b34374327511e32e99c871652ee1b1bb6b662737416f7d4864505a59 |