CKTIS / Python
logging.Formatter
Converts a log record into a line of text using declared record attributes.
Version: Python 3.14; repository image, production runtime not attested
Syntax
logging.Formatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)Converts a log record into a line of text using declared record attributes.
The message attribute is obtained by interpolating the record arguments. A custom format can omit unstable timestamps.
The style setting selects percent, braces or dollar syntax for the record layout, while LogRecord.getMessage still interpolates msg and args using percent-style formatting. datefmt controls asctime and defaults supplies missing custom fields. The example formats a warning record as WARNING|count=2. validate=True checks fmt syntax against style at construction. formatTime converts record.created for asctime using datefmt. An exception traceback from exc_info and the current logging stack requested with stack_info are independently appended.
import logging
r=logging.LogRecord('app',logging.WARNING,'',0,'count=%d',(2,),None)
fmt=logging.Formatter('{levelname}|{message}|{tenant}',style='{',defaults={'tenant':'guest'})
assert fmt.format(r)=='WARNING|count=2|guest' and r.message=='count=2'
try: logging.Formatter('{message}',style='%')
except ValueError: pass
else: raise AssertionError
import sys,time,io
tf=logging.Formatter('%(asctime)s %(message)s',datefmt='%Y')
tf.converter=time.gmtime
r.created=0
assert tf.format(r)=='1970 count=2'
out=io.StringIO()
logging.basicConfig(stream=out,format='%(message)s',level=logging.DEBUG,force=True)
try: raise ValueError('x')
except ValueError: logging.error('both',exc_info=True,stack_info=True)
assert 'Traceback (most recent call last)' in out.getvalue() and 'Stack (most recent call last)' in out.getvalue()
Examples
import logging
fmt = logging.Formatter("%(levelname)s|%(message)s")
record = logging.LogRecord("sample", logging.WARNING, "", 0, "count=%d", (2,), None)
print(fmt.format(record))
Result
WARNING|count=2
The style setting selects percent, braces or dollar syntax for the record layout, while LogRecord.getMessage still interpolates msg and args using percent-style formatting. datefmt controls asctime and defaults supplies missing custom fields. The example formats a warning record as WARNING|count=2. validate=True checks fmt syntax against style at construction. formatTime converts record.created for asctime using datefmt. An exception traceback from exc_info and the current logging stack requested with stack_info are independently appended.