logging — application logging

Isolated loggers, StringIO handlers, lazy %-formatting, and logging error handling, checked on Python 3.13.12 without global side effects or timestamps.

モジュールページの本文は現在英語です。

The logging examples use a named logger, propagate=False, and a StreamHandler bound to io.StringIO. They do not call logging.basicConfig, they do not attach handlers to the root logger, and the formatter has no asctime field, so the output has no clock-dependent text.

Logger.debug(msg, *args) formats msg % args only if a handler will actually emit the record. Examples were checked on Python 3.13.12.

Examples were checked against Python 3.13. See the official documentation for the complete API.

Python reference overview →

Isolated loggers and lazy formatting

getLogger("python-ref.demo") returns a named logger. After propagate is set to False and a formatter of "%(levelname)s %(name)s %(message)s" is attached, info records appear as a stable line. The Probe helper counts __str__ calls.

When the logger level is INFO, logger.debug("debug %s", probe) does not call __str__. logger.info does. If the logger is then set to DEBUG but the handler stays at INFO, a debug record is still not formatted. Formatting is deferred until a handler emits the record, not merely until the logger is enabled for that level.

getLogger, Logger.debug, Logger.info, StreamHandler, Formatter

logging.getLogger(name=None)
Logger.debug(msg, *args, **kwargs)
Logger.info(msg, *args, **kwargs)
logging.StreamHandler(stream=None)
logging.Formatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)

Log to an isolated named logger, and format %-arguments only when a handler emits the record.

ParameterDescription
nameThe logger name. None would return the root logger; the example uses a private name and sets propagate=False.
msg, *argsThe message is a % format string. Arguments are converted with % only if the record is emitted.
streamThe StreamHandler destination. io.StringIO keeps the example off the process stdout until the script prints the buffer.

Returns: getLogger returns a Logger. The example prints the captured log line and the __str__ call counts.

  • Do not write logger.debug(f"... {expensive()}") if you want the expensive work skipped; the f-string is built before the call. The lazy form is logger.debug("... %s", arg).
python
import io
import logging

class Probe:
    def __init__(self, label):
        self.label = label
        self.calls = 0

    def __str__(self):
        self.calls += 1
        return self.label

logger = logging.getLogger("python-ref.demo")
logger.handlers.clear()
logger.setLevel(logging.INFO)
logger.propagate = False
buffer = io.StringIO()
handler = logging.StreamHandler(buffer)
handler.setLevel(logging.INFO)
handler.setFormatter(logging.Formatter("%(levelname)s %(name)s %(message)s"))
logger.addHandler(handler)

debug_probe = Probe("D")
info_probe = Probe("I")
logger.debug("debug %s", debug_probe)
logger.info("info %s", info_probe)
print(buffer.getvalue(), end="")
print("debug-str-calls", debug_probe.calls)
print("info-str-calls", info_probe.calls)

buffer.seek(0)
buffer.truncate(0)
logger.setLevel(logging.DEBUG)
filtered = Probe("H")
logger.debug("maybe %s", filtered)
print("filtered-str-calls", filtered.calls)
print("after-filter-empty", buffer.getvalue() == "")

Expected output

INFO python-ref.demo info I
debug-str-calls 0
info-str-calls 1
filtered-str-calls 0
after-filter-empty True

Official documentation →

When a log argument raises

If __str__ of a logging argument raises while the record is being formatted, the handler calls handleError. With the default logging.raiseExceptions is True, Python writes a traceback to sys.stderr, starting with "--- Logging error ---", and the logging call then returns. The program continues; the failed record is not written to the handler stream.

The example captures sys.stderr itself so the recorded output contains only booleans, not a traceback that would include local library paths. This is the measured 3.13.12 behavior for StreamHandler, not a promise about every custom handler.

Handler.handleError, logging.raiseExceptions

Handler.handleError(record)
logging.raiseExceptions

A formatting error is reported on sys.stderr and does not abort the program when raiseExceptions is True.

Returns: The logging call returns normally after handleError. The handler buffer stays empty for the failed record.

  • The example does not set raiseExceptions to False. That flag changes whether handleError prints a traceback; it is a process-wide setting, so the example only reads it.
python
import io
import logging
import sys

class Boom:
    def __str__(self):
        raise RuntimeError("boom")

logger = logging.getLogger("python-ref.errors")
logger.handlers.clear()
logger.setLevel(logging.INFO)
logger.propagate = False
buffer = io.StringIO()
handler = logging.StreamHandler(buffer)
handler.setFormatter(logging.Formatter("%(levelname)s %(message)s"))
logger.addHandler(handler)

stderr = io.StringIO()
saved = sys.stderr
sys.stderr = stderr
try:
    logger.info("value %s", Boom())
finally:
    sys.stderr = saved

print("continued", "yes")
print("log-buffer-empty", buffer.getvalue() == "")
print("raiseExceptions", logging.raiseExceptions)
text = stderr.getvalue()
print("has-logging-error", text.startswith("--- Logging error ---"))
print("has-boom", "RuntimeError: boom" in text)

Expected output

continued yes
log-buffer-empty True
raiseExceptions True
has-logging-error True
has-boom True

Official documentation →