Skip to content

structure log

Logfirehas a built-in structlog processor that can be used to issue Logfire logs for each structlog event.

main.py
from dataclasses import dataclass

import structlog
import logfire

logfire.configure()

structlog.configure(
    processors=[
        structlog.contextvars.merge_contextvars,
        structlog.processors.add_log_level,
        structlog.processors.StackInfoRenderer(),
        structlog.dev.set_exc_info,
        structlog.processors.TimeStamper(fmt='%Y-%m-%d %H:%M:%S', utc=False),
        logfire.StructlogProcessor(),
        structlog.dev.ConsoleRenderer(),
    ],
)
logger = structlog.get_logger()


@dataclass
class User:
    id: int
    name: str


logger.info('Login', user=User(id=42, name='Fred'))
#> 2024-03-22 12:57:33 [info     ] Login                          user=User(id=42, name='Fred')

Logfire processormust bebefore the last processor to render logs instructlogconfiguration.

By default,LogfireProcessor shown above disables console logging for logfire, so you can use an existing logger configured for structlog, or LogfireProcessor(console_log=True) if you want to log with logfire.

Attention

Location parameters are not collected by the processor as attributes because they are already part of the event message when the processor is invoked.

If you have the following conditions:

logger.error('Hello %s!', 'Fred')
#> 2024-03-22 13:39:26 [error    ] Hello Fred!

The string 'Fred' is not collected as an attribute by the processor, it is simply formatted with a message.


本文总阅读量次