Sub topic 6
Formatters: how records look
This chapter assumes you can create a logger, attach a handler, and know the level names from the earlier chapters. It covers how a logging.Formatter turns a LogRecord into the text a handler writes, and the errors that come up when you customize that step.
Where the formatter runs
A logger creates a LogRecord, an object holding everything about one log call. Each handler that accepts the record asks its own formatter to convert it to a string. Formatting happens per handler, not per logger. A logger has no setFormatter method.
If a handler has no formatter, it uses a default one that outputs only %(message)s. That is why a bare StreamHandler prints no level or time.
Format strings and LogRecord attributes
A Formatter takes a format string that names LogRecord attributes. Each placeholder is filled from the record.
import logging
handler = logging.StreamHandler()
handler.setFormatter(
logging.Formatter(
"%(asctime)s | %(levelname)-8s | %(name)s:%(lineno)d | %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
)
logger = logging.getLogger("myapp.orders")
logger.setLevel(logging.INFO)
logger.addHandler(handler)
logger.info("Order %s created", 42)This prints a line like 2026-11-26 11:38:55 | INFO | myapp.orders:12 | Order 42 created. The line number depends on where the call sits in your file. %(levelname)-8s pads the level name to 8 characters so columns line up.
The attributes you will use most:
| Attribute | Meaning |
|---|---|
| `asctime` | Human-readable creation time, built by `formatTime` |
| `levelname` | `DEBUG`, `INFO`, `WARNING`, `ERROR`, or `CRITICAL` |
| `name` | Name of the logger that created the record |
| `message` | The result of `msg % args` |
| `module`, `filename`, `pathname` | Where the call was made |
| `funcName`, `lineno` | Function name and line number of the call |
| `process`, `processName` | Process ID and name |
| `thread`, `threadName` | Thread ID and name |
| `created`, `msecs` | Creation time as epoch seconds, and its millisecond part |
The formatter computes message and asctime only when it formats the record. Until then, record.msg and record.args stay separate. This is why you should write logger.info("Order %s", n) and not logger.info(f"Order {n}"). The first form skips the string work when the record is filtered out, and it keeps the template available to tools that group similar messages.
Three format styles
The style argument selects the placeholder syntax of the format string: "%" (default), "{" (str.format), or "$" (string.Template).
import logging
formatter = logging.Formatter(
"{asctime} {levelname:<8} {name}: {message}", style="{"
)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger = logging.getLogger("styles")
logger.setLevel(logging.INFO)
logger.addHandler(handler)
logger.info("Still uses percent style here: %s", "ok")By default Formatter validates the format string when you construct it. A wrong placeholder, such as a { style string with style="%", raises ValueError at startup instead of failing on the first log call.
Controlling time
datefmt is a time.strftime pattern for asctime. Without it, the output looks like 2026-11-26 11:38:55,414, with a comma before the milliseconds. Milliseconds are only appended when datefmt is not given. If you give datefmt, add them yourself if you need them, using %(msecs)03d in the format string.
Timestamps use local time by default. To log in UTC, set the formatter's converter, and optionally change the millisecond format:
import logging
import time
formatter = logging.Formatter("%(asctime)s %(message)s")
formatter.converter = time.gmtime
formatter.default_msec_format = "%s.%03d"
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger = logging.getLogger("utc")
logger.setLevel(logging.INFO)
logger.addHandler(handler)
logger.info("Timestamps are in UTC")Set converter on the instance, as above, or on a subclass. Setting it on logging.Formatter itself changes every formatter in the process.
Custom attributes and defaults
Anything you pass in extra becomes an attribute on the record, so the format string can use it.
import logging
formatter = logging.Formatter(
"%(levelname)s [%(request_id)s] %(message)s",
defaults={"request_id": "-"},
)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger = logging.getLogger("web")
logger.setLevel(logging.INFO)
logger.addHandler(handler)
logger.info("Starting")
logger.info("Handling", extra={"request_id": "req-9"})The output is INFO [-] Starting followed by INFO [req-9] Handling. The defaults argument (Python 3.10 and later) supplies a value when the record lacks the attribute. Without it, the first call fails, as described in the next section.
Common errors
- Missing attribute. If the format string uses
%(request_id)sand a record has no such attribute, formatting raises an error. The logging system catches it inHandler.handleError, prints a--- Logging error ---traceback to stderr, and your program continues. The log line is lost. Usedefaults, a filter that sets the attribute, or always passextra. - Clashing
extrakeys.extrakeys cannot reuse existing record attributes such asname,message, orasctime. Logging raisesKeyErrorwith "Attempt to overwrite". Pick distinct names. - Formatter on the wrong object. Calling
logger.setFormatter(...)raisesAttributeError. Set formatters on handlers. - Shared exception text. When a record has
exc_info,Formatter.formatappends the traceback after the message. It caches the traceback text inrecord.exc_textthe first time any formatter renders it. A second handler with a differentformatExceptionthen reuses the cached text. If handlers must show tracebacks differently, clearrecord.exc_textin a customformat, or keep the traceback logic in one formatter class. - Format string with no time. The formatter only calls
formatTimewhen the format string contains%(asctime)s(usesTime()checks this). If you expect a timestamp and see none, check the string.
Customizing the output
Override one of three methods, from narrowest to widest:
formatTime(record, datefmt)changes howasctimeis built.formatException(exc_info)changes how the traceback text is built.format(record)builds the whole line. Callsuper().format(record)to reuse the standard behavior.
A common case is adding a computed field. This formatter marks slow operations:
import logging
class DurationFormatter(logging.Formatter):
def format(self, record):
duration = getattr(record, "duration_ms", None)
base = super().format(record)
if duration is None:
return base
flag = " SLOW" if duration > 500 else ""
return f"{base} ({duration} ms{flag})"
handler = logging.StreamHandler()
handler.setFormatter(DurationFormatter("%(levelname)s %(message)s"))
logger = logging.getLogger("timing")
logger.setLevel(logging.INFO)
logger.addHandler(handler)
logger.info("Query finished", extra={"duration_ms": 750})
logger.info("Cache hit")The first call prints INFO Query finished (750 ms SLOW) and the second prints INFO Cache hit. getattr with a default keeps records that lack the field from failing.
Exercises
Exercise
A handler's formatter uses "%(request_id)s", and a code path calls logger.info("Starting") without extra. What happens to the program and to the log line, and what are two ways to prevent it?
Show answer
Formatting the record fails. The logging system reports "--- Logging error ---" with a traceback on stderr, the log line is not written, and the program keeps running. Prevent it by passing defaults={"requestid": "-"} to the Formatter (Python 3.10 and later), by adding a filter that sets record.requestid on every record, or by always passing extra with request_id.
Exercise
You set datefmt="%H:%M:%S" and want milliseconds in the timestamp. How do you get them, and why does defaultmsecformat not help here?
Show answer
Put %(msecs)03d in the format string, for example "%(asctime)s.%(msecs)03d". defaultmsecformat is applied only when datefmt is not given, so it has no effect once you set datefmt.