Python Glossary Русский

all Python 3loggingterm

logging.Formatter

formatting

Sets the layout of a log line: the time, the level, the logger name, the message and so on. It is attached to a Handler.

Syntax

fmt = logging.Formatter(fmt=None, datefmt=None, style='%')

A formatter belongs to a handler via handler.setFormatter(); Logger has no such method at all, which is the usual reason a custom format seems to be ignored. Placeholders default to %-style, so writing {message} in braces does nothing unless you pass style='{'. Supplying your own datefmt drops the milliseconds from the timestamp — add %(msecs)d yourself if you still want them.

Examples

import logging
handler = logging.StreamHandler()
formatter = logging.Formatter(
fmt='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
handler.setFormatter(formatter)
logging.getLogger().addHandler(handler)

See also

Open in the full glossarydocs.python.orgReport an inaccuracy