Skip to content

adjunct.slog

Simple structured logging with spans.

This module provides utilities for structured logging in JSON and Logfmt format, including the ability to create logging spans that carry contextual metadata.

It builds on Python's built-in logging module.

To configure logging to use structured logging, set up a logger with JSONFormatter:

import logging

from adjunct.slog JSONFormatter, M, span


logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
JSONFormatter.configure_handler(handler)
logger.addHandler(handler)

Both M and span can then be used to add structured metadata to log records:

logger.info(M("User logged in", user="alice"))  # Log with metadata
with span(request_id="12345", user_id="alice"):  # Log within a span
    logger.info(M("User action", action="update_profile"))

M and JSONFormatter work together to produce log records that include the specified metadata and span context, but can both be used independently if desired. Using M will produce a stringified message that includes the metadata in JSON, even without JSONFormatter.

An alternative is LogfmtFormatter, which formats log records in logfmt format. It works just like JSONFormatter, but produces log records in logfmt instead of JSON.

Note

The keys spanId and parentSpanId are reserved for span tracking and should not be used in metadata passed to M or span. They are named to match OpenTelemetry conventions, though this module does not implement OpenTelemetry itself nor aims to be compatible with it.

span = _SpanStack() module-attribute

A context manager for logging spans.

Functions:

Name Description
extend

Add additional context to the current span. As this modifies the current span, using it within a span may lead to confusing logs; it is generally not recommended. It accepts the same key-value pairs as the context manager.

Examples:

>>> with slog.span(request_id="12345", user_id="alice"):
...    logger.info(slog.M("User action", action="update_profile"))

JSONFormatter

Bases: _BaseFormatter

A logging formatter that outputs JSON log records.

LogfmtFormatter

Bases: _BaseFormatter

A logging formatter that outputs log records in logfmt format.

M

A message with some attached metaadata for structured logging.

When stringified, this produces a JSON-like string that can be parsed by log processors.

If used with JSONFormatter, it'll merge the metadata into the log record.

Parameters:

Name Type Description Default
message str

The main log message.

required
**metadata Scalar

Additional key-value pairs to attach to the log record.

{}