Skip to content

Formatter

Definition of the central SyslogFormatter class.

SyslogFormatter

Bases: Formatter

Log formatter class for syslog-style log messages.

It ensures that a syslog PRI part is prepended to every log message. The PRI code is calculated as the facility value (provided in the constructor) multiplied by 8 plus the severity value, which is derived from the level of each log record. See the relevant section of RFC 3164 for details about syslog standard.

The formatter is also equipped by default to format log messages into one-liners, such that for example exception messages and stack traces included in a log record do not result in the message spanning multiple lines in the final output.

It also makes it possible to automatically append additional details to a log message, if the log record exceeds a specified level.

__init__

__init__(
    fmt: str | None = None,
    datefmt: str | None = None,
    style: StyleKey = "%",
    validate: bool = True,
    *,
    defaults: AnyMap | None = None,
    facility: int = USER,
    line_break_repl: str | None = " --> ",
    level_formats: LevelFmtMap | None = None
) -> None

Validates the added formatter constructor arguments.

For details about the base class' constructor parameters, the official docs provide full explanations.

Parameters:

Name Type Description Default
fmt str | None

A format string in the given style for the logged output as a whole. The possible mapping keys are drawn from the logging.LogRecord object's attributes.

By default %(message)s | %(name)s will be used and passed to the parent __init__. If any custom string is passed, that string is passed through unchanged to the parent __init__.

None
datefmt str | None

Passed through to the parent __init__.

None
style StyleKey

Passed through to the parent __init__.

'%'
validate bool

If True (default), incorrect or mismatched fmt and style will raise a ValueError; for example, logging.Formatter('%(asctime)s - %(message)s', style='{').

Also, if True, a non-standard facility value (i.e. not between 0 and 24) will raise a NonStandardSyslogFacility error. The argument is always passed through to the parent __init__.

True
defaults AnyMap | None

Passed through to the parent __init__ on Python >=3.10. Ignored on Python <3.10.

None
facility int

Used to calculate the number in the PRI part at the very start of each log message. This argument should be an integer between 0 and 24. The facility value is multiplied by 8 and added to the numerical value of the severity that corresponds to the log level of the message.

Details about accepted numerical values can be found in section 4.1.1 of RFC 3164. Defaults to USER.

USER
line_break_repl str | None

To prevent a single log message taking up more than one line, every line-break (and consecutive whitespace) in the final log message will be replaced with the string provided here. This is useful because log records that include exception information for example normally result in the multi-line traceback being included in the log message.

Passing None disables this behavior. This means the default (multi-line) exception formatting will be used.

Defaults to ' --> '.

' --> '
level_formats LevelFmtMap | None

If provided a mapping of log level thresholds to format strings, the formatter will prioritize the format with the highest level threshold for all log records at or above that level.

For example, say you pass the following dictionary:

{"WARNING": "foo %(message)s",
 "ERROR":   "bar %(message)s"}
Log records with the level ERROR or higher will be formatted with the bar %(message)s format; records with a level of WARNING or higher but below ERROR will be formatted with the foo %(message)s format; those with a level below WARNING will use the normal format provided via the fmt argument.

The order of the provided mapping is irrelevant. If such a mapping is passed, the formats should conform to the specified style, just like the fmt argument; if any of them does not and validate is True, a ValueError is raised.

If passed None (default) or an empty mapping, the formatter will use the normal provided fmt for all log messages.

None

Raises:

Type Description
NonStandardSyslogFacility

If validate was set to True and the facility passed was not an integer between 0 and 23.

ValueError

If validate was set to True and the provided fmt or any of the values in the level_formats mapping (if provided) do not match the specified style.

format

format(record: LogRecord) -> str

Formats a record to be compliant with syslog PRI (log level/severity).

Ensures that line-breaks in the exception message are replaced to ensure it fits into a single line, unless this behavior was disabled.

The rest of the logic is the same as in the parent method. The record's attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.getMessage. If the formatting string uses the time (as determined by a call to usesTime), formatTime is called to format the event time. If there is exception information, it is formatted using formatException and appended to the message. If stack information is available, it is appended after the exception information, using formatStack to transform it if necessary.

Parameters:

Name Type Description Default
record LogRecord

The logging.LogRecord to format as text

required

Returns:

Type Description
str

The final log message constructed from the log record

formatMessage

formatMessage(record: LogRecord) -> str

Takes a log record and produces a formatted message from it.

If different level styles have been set, the one mapped to the highest level at or below that of the record will be used to format it.

Otherwise the parent method is called.

Parameters:

Name Type Description Default
record LogRecord

The log record to format

required

Returns:

Type Description
str

The formatted log message as text