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.
| Parameter | Description |
|---|---|
name | The logger name. None would return the root logger; the example uses a private name and sets propagate=False. |
msg, *args | The message is a % format string. Arguments are converted with % only if the record is emitted. |
stream | The 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).
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