Saltar a contenido

Logging

Structured logging utilities built on structlog.

configure_logging

configure_logging(
    level: LogLevel = LogLevel.INFO,
    format: LogFormat = LogFormat.JSON,
    stream: Any | None = None,
) -> None

Configure structured logging for the application.

This should be called once at application startup. Subsequent calls will reconfigure logging (useful for testing).

Parameters:

Name Type Description Default
level LogLevel

The minimum log level to output

INFO
format LogFormat

The output format (JSON for production, CONSOLE for development)

JSON
stream Any | None

Output stream (defaults to sys.stdout)

None
Example
# Local development
configure_logging(level=LogLevel.DEBUG, format=LogFormat.CONSOLE)

# Production
configure_logging(level=LogLevel.INFO, format=LogFormat.JSON)

get_logger

get_logger(name: str) -> structlog.stdlib.BoundLogger

Get a structured logger for the given module name.

This returns a structlog BoundLogger that wraps the stdlib logger. If logging hasn't been configured, it will use sensible defaults.

Parameters:

Name Type Description Default
name str

The logger name (typically name)

required

Returns:

Type Description
BoundLogger

A structured logger instance

Example
logger = get_logger(__name__)
logger.info("processing_started", deployment_id="momentum_v1")

LogLevel

Bases: StrEnum

Log level enumeration.

LogFormat

Bases: StrEnum

Log format enumeration.

Context Management

add_context

add_context(**kwargs: Any) -> None

Add persistent context to all subsequent log messages.

Context is stored in a context variable and automatically added to all log messages. Use this for values like correlation_id or deployment_id that should appear in all logs.

Parameters:

Name Type Description Default
**kwargs Any

Key-value pairs to add to context

{}
Example
add_context(correlation_id="abc-123", deployment_id="momentum_v1")
logger.info("processing")  # Will include correlation_id and deployment_id

clear_context

clear_context() -> None

Clear all context variables.

Call this to reset the logging context, typically at the start of a new request or iteration.

Example
clear_context()
add_context(correlation_id="new-123")

with_context

with_context(**kwargs: Any) -> AbstractContextManager[None]

Context manager for temporary logging context.

Adds context for the duration of a block, then removes it.

Parameters:

Name Type Description Default
**kwargs Any

Key-value pairs to add temporarily

{}
Example
with with_context(tx_hash="0x123"):
    logger.info("signing")  # Includes tx_hash
    logger.info("submitting")  # Includes tx_hash
logger.info("done")  # Does not include tx_hash

Returns:

Type Description
AbstractContextManager[None]

Context manager