Search code examples
pythonstructlog

Structlog use in modules and for console


Two related questions about using the production-ready configuration - https://www.structlog.org/en/stable/performance.html:

i. How to use this configuration across different modules (files)?

ii. How to ensure .info logger output is displayed on the console (terminal) from inside a Class or def function (right now it isn't displaying)?

import logging
import structlog

logging.basicConfig(
    format="%(message)s",
    stream=sys.stdout,
    level=logging.INFO,
)

structlog.configure(
    cache_logger_on_first_use=True,
    wrapper_class=structlog.make_filtering_bound_logger(logging.INFO),
    processors=[
        structlog.threadlocal.merge_threadlocal_context,
        structlog.processors.add_log_level,
        structlog.processors.format_exc_info,
        structlog.processors.TimeStamper(fmt="iso", utc=False),
        structlog.processors.JSONRenderer(serializer=orjson.dumps),
    ],
    logger_factory=structlog.BytesLoggerFactory(),
)

Solution

  • If you use structlog.configure(), the configuration is global to your application and valid for all modules.

    Please note that your logging.basicConfig() has no effect, since your structlog config doesn't route the log entries to the standard library.

    Your second question needs more context, logging works from functions and classes, there is nothing special about it.