Skip to content

Logging

Integration with the standard library logging module.

LogfireLoggingHandler

LogfireLoggingHandler(
    level: int | str = NOTSET,
    fallback: Handler = StreamHandler(),
    logfire_instance: Logfire | None = None,
)

Bases: Handler

A logging handler that sends logs to Logfire.

Source code in logfire/integrations/logging.py
57
58
59
60
61
62
63
64
65
66
67
def __init__(
    self,
    level: int | str = NOTSET,
    fallback: LoggingHandler = StreamHandler(),
    logfire_instance: Logfire | None = None,
) -> None:
    super().__init__(level=level)
    self.fallback = fallback
    self.logfire_instance = (logfire_instance or logfire.DEFAULT_LOGFIRE_INSTANCE).with_settings(
        custom_scope_suffix=self.custom_scope_suffix
    )

emit

emit(record: LogRecord) -> None

Send the log to Logfire.

Parameters:

Name Type Description Default

record

LogRecord

The log record to send.

required
Source code in logfire/integrations/logging.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def emit(self, record: LogRecord) -> None:
    """Send the log to Logfire.

    Args:
        record: The log record to send.
    """
    if is_instrumentation_suppressed():
        self.fallback.handle(record)
        return

    attributes = self.fill_attributes(record)

    self.logfire_instance.log(
        msg_template=attributes.pop(ATTRIBUTES_MESSAGE_TEMPLATE_KEY, record.msg),
        level=LOGGING_TO_OTEL_LEVEL_NUMBERS.get(record.levelno, record.levelno),
        attributes=attributes,
        exc_info=record.exc_info,
    )

fill_attributes

fill_attributes(record: LogRecord) -> dict[str, Any]

Fill the attributes to send to Logfire.

This method can be overridden to add more attributes.

Parameters:

Name Type Description Default

record

LogRecord

The log record.

required

Returns:

Type Description
dict[str, Any]

The attributes for the log record.

Source code in logfire/integrations/logging.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def fill_attributes(self, record: LogRecord) -> dict[str, Any]:
    """Fill the attributes to send to Logfire.

    This method can be overridden to add more attributes.

    Args:
        record: The log record.

    Returns:
        The attributes for the log record.
    """
    attributes = {k: v for k, v in record.__dict__.items() if k not in RESERVED_ATTRS}
    attributes['code.filepath'] = record.pathname
    attributes['code.lineno'] = record.lineno
    attributes['code.function'] = record.funcName

    attributes[ATTRIBUTES_MESSAGE_KEY], args = _format_message(record)
    attributes.update(args)

    return attributes