from contextlib import _GeneratorContextManager
from typing import Protocol
import orjson
import structlog
import structlog.dev
from structlog.processors import ExceptionRenderer
from structlog.typing import FilteringBoundLogger
from structlog_config.formatters import (
PathPrettifier,
WheneverFormatter,
add_fastapi_context,
beautiful_traceback_exception_formatter,
get_json_exception_formatter,
logger_name,
simplify_activemodel_objects,
)
from . import (
hook,
packages,
trace, # noqa: F401 (import has side effects for trace level setup)
)
from .constants import NO_COLOR, package_logger
from .environments import is_pytest
from .factory import get_logger_factory
from .levels import get_environment_log_level_as_string
from .stdlib_logging import (
redirect_stdlib_loggers,
)
from .tee import (
tee_logs, # noqa: F401
wrap_logger_factory_for_tee,
)
from .trace import setup_trace
from .version import __version__ as __version__
from .warnings import redirect_showwarnings
_CONFIGURATION_FINALIZED = False
[docs]
def log_processors_for_mode(json_logger: bool) -> list[structlog.types.Processor]:
"""
Determine what the "final" processes in the pipeline should be to render the log to the output device.
- If JSON, then structure exceptions as dicts and render as JSON
- If not JSON, then use the ConsoleRenderer with a nice exception formatter.
"""
if json_logger:
def orjson_dumps_sorted(value, *args, **kwargs):
"sort_keys=True is not supported, so we do it manually"
# kwargs includes a default fallback json formatter
return orjson.dumps(
value,
# starlette-context includes non-string keys (enums), which is why we need to set the options in this way
# TODO do we need to sort the keys here? this will cost us in CPU time :/
option=orjson.OPT_SORT_KEYS | orjson.OPT_NON_STR_KEYS,
**kwargs,
)
exception_formatter = get_json_exception_formatter()
return [
# ExceptionRenderer transforms the raw `exc_info` tuple into a formatted `exception` field.
# We omit `structlog.processors.format_exc_info` here to use this structured renderer instead.
# In production, we keep rendering simple/short since Sentry handles the heavy lifting.
# https://www.structlog.org/en/stable/exceptions.html
ExceptionRenderer(exception_formatter),
# in prod, we want logs to be rendered as JSON payloads
structlog.processors.JSONRenderer(serializer=orjson_dumps_sorted),
]
# Passing None skips the ConsoleRenderer default, so use the explicit dev default.
exception_formatter = structlog.dev.default_exception_formatter
# if we have beautiful traceback installed, use it
if packages.beautiful_traceback:
exception_formatter = beautiful_traceback_exception_formatter
return [
structlog.dev.ConsoleRenderer(
colors=not NO_COLOR,
exception_formatter=exception_formatter,
)
]
[docs]
def get_default_processors(json_logger: bool) -> list[structlog.types.Processor]:
"""
Return the default list of log processors for structlog configuration.
This includes any "final" processors to render the log as json or not.
"""
processors = [
# although this is stdlib, it's needed, although I'm not sure entirely why
structlog.stdlib.add_log_level,
structlog.contextvars.merge_contextvars,
logger_name,
add_fastapi_context if packages.starlette_context else None,
simplify_activemodel_objects
if packages.activemodel and packages.typeid
else None,
PathPrettifier(),
WheneverFormatter() if packages.whenever else None,
structlog.processors.TimeStamper(fmt="iso", utc=True),
# add `stack_info=True` to a log and get a `stack` attached to the log
structlog.processors.StackInfoRenderer(),
*log_processors_for_mode(json_logger),
]
return [processor for processor in processors if processor is not None]
[docs]
class LoggerWithContext(FilteringBoundLogger, Protocol):
"""
A customized bound logger class that adds easy-to-remember methods for adding context.
We don't use a real subclass because `make_filtering_bound_logger` has some logic we don't
want to replicate.
"""
[docs]
def context(self, *args, **kwargs) -> _GeneratorContextManager[None, None, None]:
"context manager to temporarily set and clear logging context"
...
[docs]
def local(self, *args, **kwargs) -> None:
"set thread-local context"
...
[docs]
def clear(self) -> None:
"clear thread-local context"
...
[docs]
def trace(self, *args, **kwargs) -> None:
"trace level logging"
...
# TODO this may be a bad idea, but I really don't like how the `bound` stuff looks and how to access it, way too ugly
[docs]
def add_simple_context_aliases(log) -> LoggerWithContext:
log.context = structlog.contextvars.bound_contextvars
log.local = structlog.contextvars.bind_contextvars
log.clear = structlog.contextvars.clear_contextvars
return log
[docs]
def get_logger(*args, **kwargs) -> LoggerWithContext:
"""
Get a structlog logger with the same context alias methods as the logger returned by `configure_logger`.
This is useful in cases where you want to get a logger without configuring it (e.g. in libraries or in tests).
"""
log = structlog.get_logger(*args, **kwargs)
log = add_simple_context_aliases(log)
return log