Skip to content

Class swarmauri_standard.logger_formatters.ContextualFormatter.ContextualFormatterImpl

swarmauri_standard.logger_formatters.ContextualFormatter.ContextualFormatterImpl

ContextualFormatterImpl(
    fmt=None,
    datefmt=None,
    context_keys=None,
    context_as_prefix=False,
    context_separator=" ",
    context_prefix="[",
    context_suffix="]",
    context_item_format="{key}={value}",
    include_empty_context=False,
    **kwargs,
)

Bases: Formatter

Implementation of the contextual formatter logic.

This class extends the standard logging.Formatter to include contextual information from LogRecord attributes.

Initialize the contextual formatter.

PARAMETER DESCRIPTION
fmt

The base format string

TYPE: Optional[str] DEFAULT: None

datefmt

The date format string

TYPE: Optional[str] DEFAULT: None

context_keys

List of attribute names to extract from LogRecord

TYPE: List[str] DEFAULT: None

context_as_prefix

Whether to format context as a prefix

TYPE: bool DEFAULT: False

context_separator

Separator between context items

TYPE: str DEFAULT: ' '

context_prefix

Prefix for the entire context section

TYPE: str DEFAULT: '['

context_suffix

Suffix for the entire context section

TYPE: str DEFAULT: ']'

context_item_format

Format for each context item (when not prefix mode)

TYPE: str DEFAULT: '{key}={value}'

include_empty_context

Whether to include context section when all values are missing

TYPE: bool DEFAULT: False

**kwargs

Additional arguments passed to logging.Formatter

DEFAULT: {}

Source code in swarmauri_standard/logger_formatters/ContextualFormatter.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def __init__(
    self,
    fmt: Optional[str] = None,
    datefmt: Optional[str] = None,
    context_keys: List[str] = None,
    context_as_prefix: bool = False,
    context_separator: str = " ",
    context_prefix: str = "[",
    context_suffix: str = "]",
    context_item_format: str = "{key}={value}",
    include_empty_context: bool = False,
    **kwargs,
):
    """
    Initialize the contextual formatter.

    Args:
        fmt: The base format string
        datefmt: The date format string
        context_keys: List of attribute names to extract from LogRecord
        context_as_prefix: Whether to format context as a prefix
        context_separator: Separator between context items
        context_prefix: Prefix for the entire context section
        context_suffix: Suffix for the entire context section
        context_item_format: Format for each context item (when not prefix mode)
        include_empty_context: Whether to include context section when all values are missing
        **kwargs: Additional arguments passed to logging.Formatter
    """
    super().__init__(fmt=fmt, datefmt=datefmt, **kwargs)
    self.context_keys = context_keys or ["request_id", "user_id"]
    self.context_as_prefix = context_as_prefix
    self.context_separator = context_separator
    self.context_prefix = context_prefix
    self.context_suffix = context_suffix
    self.context_item_format = context_item_format
    self.include_empty_context = include_empty_context

context_keys instance-attribute

context_keys = context_keys or ['request_id', 'user_id']

context_as_prefix instance-attribute

context_as_prefix = context_as_prefix

context_separator instance-attribute

context_separator = context_separator

context_prefix instance-attribute

context_prefix = context_prefix

context_suffix instance-attribute

context_suffix = context_suffix

context_item_format instance-attribute

context_item_format = context_item_format

include_empty_context instance-attribute

include_empty_context = include_empty_context

format

format(record)

Format the specified record as text with added context.

PARAMETER DESCRIPTION
record

The log record to format

TYPE: LogRecord

RETURNS DESCRIPTION
str

The formatted log message with context

TYPE: str

Source code in swarmauri_standard/logger_formatters/ContextualFormatter.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
def format(self, record: logging.LogRecord) -> str:
    """
    Format the specified record as text with added context.

    Args:
        record: The log record to format

    Returns:
        str: The formatted log message with context
    """
    # First get the standard formatted message
    formatted_message = super().format(record)

    # Extract context values from the record
    context_values = {}
    for key in self.context_keys:
        # Check if the attribute exists in the record
        if hasattr(record, key):
            value = getattr(record, key)
            if value is not None:
                context_values[key] = value

    # If no context values found and we don't include empty context, return the original message
    if not context_values and not self.include_empty_context:
        return formatted_message

    # Format the context section - even if empty with include_empty_context
    context_str = self._format_context(context_values)

    # For empty context with include_empty_context=True
    if not context_values and self.include_empty_context:
        context_str = f"{self.context_prefix}{self.context_suffix}"

    # Add the context to the message
    if self.context_as_prefix:
        # Add as prefix to the message
        return f"{context_str} {formatted_message}"
    else:
        # Add after the log level but before the message content
        if ": " in formatted_message:
            # Format like "INFO: [context] message"
            level_part, message_part = formatted_message.split(": ", 1)
            return f"{level_part}: {context_str} {message_part}"
        elif "] " in formatted_message:
            # Format like "[logger][INFO] [context] message"
            parts = formatted_message.split("] ", 1)
            return f"{parts[0]}] {context_str} {parts[1]}"
        else:
            # If we can't find the expected format, append to the end
            return f"{formatted_message} {context_str}"