蓝色天空网mbsky.com · 知识 · 实践 · 创造Python · 本地阅读预览
教程 / Python / 数据科学 / Python

Python logging:级别、输出路由与轮转

在真实进程中检查日志级别、配置覆盖、多路分发、过滤、轮转文件和本机邮件。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

从程序入口配置根记录器

logging 把事件等级、文本格式与输出去向分开管理。程序入口可用 basicConfig,库通常用 getLogger(__name__),由使用方决定输出设置。新进程中根记录器的初始级别是 WARNING。示例设置 DEBUG 后捕获五个级别的实际输出。

basicConfig 默认创建写向 stderr 的 StreamHandler,也可通过 filename 使用文件处理器。文件默认追加,filemode="w" 会覆盖,含中文时明确指定 encoding="utf-8"。format 定义格式,datefmt 改写时间显示。

根记录器已有处理器时,后续 basicConfig 通常直接返回。要重新配置独立应用入口,可明确使用 force=True,它会移除并关闭原处理器。修改前应确认整个进程的日志归属。

按记录器和处理器分别过滤

Logger 接收日志调用,Handler 决定去向,Formatter 决定文本样式,Filter 可按记录字段放行或拒绝。相同名称会取到同一记录器,点号形成层级。非根记录器级别为 NOTSET 时沿祖先查有效级别。根为 NOTSET 时放行各级记录,再由处理器判定。

先通过源记录器的有效级别与过滤器,再交给处理器。把记录器设为 DEBUG,文件处理器设 DEBUG,控制台处理器设 WARNING,实际 DEBUG 只进文件,WARNING 两处都能见到。记录级别描述严重程度,调用 critical 本身不会结束程序。

propagate=True 将已通过的记录直接交给祖先处理器,祖先记录器的级别和过滤器不会重跑,处理器自己的条件仍生效。源和祖先同时配置输出可能出现重复。需要隔离去向时可在相应记录器设置 propagate=False。

logger.addFilter 作用于从该记录器发出的记录。若希望祖先处理器过滤来自子记录器的消息,把过滤器加到处理器。Filter("workbench.sensor") 可按名称层级筛选。若只要 ERROR,用 levelno 等于 ERROR,阈值 ERROR 还会放行 CRITICAL。

检查真实格式字段和结构化记录

Formatter 可组合时间、等级、消息、记录器名称、文件名、行号和函数名。样例用固定 LogRecord 与 UTC 时间,逐个核对格式化字段。message 是插值后的消息,不能把原始模板当作最终输出。

程序可自定义 Formatter 输出 JSON,用字段保存等级和消息,便于后续检索。日志成本取决于等级、格式化、写入目标和负载。不要用记录成功来推断性能比 print 更高。

关闭 DEBUG 后,logger.debug("状态 %s", value) 可以省掉 value 的字符串转换。传入函数调用时,Python 仍先求出参数。f-string 也会提前格式化。若生成参数本身耗时,可先用 isEnabledFor(logging.DEBUG) 判断。本站把相同的 5000 行文本分别用 print 和启用的 logging 写入内存流,再另测被级别丢弃的调用。本次启用 logging 的写入耗时更长,被丢弃的调用写出 0 行。脚本记录每组耗时和输出校验值。实际成本随处理器、输出目标和负载变化。解压章节 ZIP 后运行 python logging-lab/logging_performance.py 可复测。

按大小、时间或邮件分发

RotatingFileHandler 位于 logging.handlers。达到 maxBytes 条件且 backupCount 大于 0 时会轮转,活动文件保留原名,旧文件按 .1、.2 等编号。实验写入五条定长数据,核对活动文件与三份备份的实际内容。大小条件不用于保证每条日志的最大长度。

TimedRotatingFileHandler 可按秒、天或午夜等时间规则轮转。到达时间边界后,还需要下一条记录触发检查。实验设定明确的 UTC 边界,再验证归档文件名与新旧正文。 本站再用 IANA 的 America/New_York 时区数据,在独立进程中用受控时钟运行真实轮转。2026 年春季切换日的两个本地午夜间隔 23 小时,秋季切换日间隔 25 小时。UTC 对照为 24 小时。静默跨过边界时没有归档。下一条日志才触发轮转,旧记录进入带起始日期的归档,新记录写入活动文件。解压后在独立环境安装 tzdata==2026.6,运行 python logging-lab/logging_midnight.py 可复测。

SMTPHandler 把日志提交到 SMTP 服务器。mailhost 可用主机名或主机与端口的二元组,fromaddr、toaddrs、subject 设置发件人、收件人列表和主题。credentials 提供账号与密码,timeout 约束通信等待。本站只用回环接收端和临时证书实测。CPython 3.12 中 secure=() 要配合有效的用户名才会发起 STARTTLS。错误口令在加密后得到 535,正确口令的日志正文和信封由本机服务核对。默认 TLS 上下文未校验服务器证书。实验另外注入验证上下文,确认未知证书被拒绝,信任指定测试证书后才收到邮件。需要验证真实服务器身份时,可用 smtplib 的 starttls(context=ssl.create_default_context()) 配置验证,真实投递需独立确认。解压章节 ZIP,在独立环境安装 cryptography==50.0.2 后运行 python logging-lab/logging_smtp.py。

重跑并核对输出去向

解压本站 ZIP 后执行 python python-logging.py。程序在临时目录生成日志,分别核对内容并关闭处理器,退出时停止本机接收端。要查看每条消息经过哪些路由,可对照每个观察的输入、操作、预期和实际结果。

下载本站 logging 实验 ZIP

所需环境:CPython 3.12 标准库

ZIP SHA256:a63fa2ff30829b126028a1ba920c92e8503216e1789a972bb4c78f777862fca7

核心类

成员、方法或字段作用和条件
logging.Logger按名称获取,决定记录是否产生及是否向祖先传播。
logging.Handler输出记录到指定目标,可有独立级别和过滤器。
logging.Formatter把 LogRecord 转成文本,可选格式与日期格式。
logging.Filter按名称层级或自定义字段过滤记录。

记录器调用

成员、方法或字段作用和条件
logger.setLevel(level)设置记录器起始阈值,非根 NOTSET 沿祖先查有效级别。
logger.debug(msg, *args)生成 DEBUG 记录,适合诊断细节。
logger.info(msg, *args)生成 INFO 记录,适合正常事件。
logger.warning(msg, *args)生成 WARNING 记录,提示异常征兆。
logger.error(msg, *args)生成 ERROR 记录,表示某项工作失败。
logger.critical(msg, *args)生成 CRITICAL 记录,表示严重事件。
logger.addHandler(handler)把处理器挂到记录器,输出仍受各路过滤条件影响。
logger.addFilter(filter)为源记录器加入过滤器,不对祖先收到的传播记录重新判断。

输出处理器

成员、方法或字段作用和条件
logging.StreamHandler(stream=None)写入文本流,默认取 stderr。
logging.FileHandler(filename, …)写入文件,按配置指定打开模式和编码。
logging.handlers.RotatingFileHandler按大小条件轮转并限制备份数。
logging.handlers.TimedRotatingFileHandler时间边界之后由输出触发轮转。
logging.handlers.SMTPHandler将日志作为邮件提交到 SMTP 服务。

级别常量

成员、方法或字段作用和条件
CRITICAL值为 50,表示严重事件。
ERROR值为 40,常用于记录失败。
WARNING值为 30,新根记录器初始阈值。
INFO值为 20,常用于正常运行状态。
DEBUG值为 10,常用于调试细节。
NOTSET值为 0。非根记录器向上查级别,根为 0 时处理各级记录。

格式化字段

成员、方法或字段作用和条件
%(asctime)s记录创建时刻的格式化文本,受 datefmt 与时区转换影响。
%(levelname)s记录的级别名称。
%(message)s将模板与参数合并后的消息。
%(name)s发出记录的记录器名称。
%(filename)s调用来源文件的文件名。
%(lineno)d记录调用位置的行号。
%(funcName)s记录调用位置的函数名称。

快速配置

成员、方法或字段作用和条件
logging.basicConfig(**kwargs)配置根记录器。已有处理器时一般不改动,force=True 可替换。

本章自编源码与运行范围

Python · 阅读源码
"""Run isolated logging routes, filters, rotation, and local SMTP delivery."""

import io
import json
import logging
import socketserver
import time
from contextlib import redirect_stderr
from email import policy
from email.parser import BytesParser
from logging.handlers import RotatingFileHandler, SMTPHandler, TimedRotatingFileHandler
from pathlib import Path
from queue import Queue
from tempfile import TemporaryDirectory
from threading import Thread


class LocalMail(socketserver.StreamRequestHandler):
    """A one-message loopback SMTP peer. It accepts no relay commands."""

    def handle(self):
        self.request.settimeout(4)
        self.wfile.write(b"220 loopback.local ready\r\n")
        envelope = []
        while command := self.rfile.readline(2048):
            verb = command.split(maxsplit=1)[0].upper() if command.strip() else b""
            if verb in {b"EHLO", b"HELO"}:
                self.wfile.write(b"250 loopback.local\r\n")
            elif verb in {b"MAIL", b"RCPT"}:
                envelope.append(command.decode("ascii").strip())
                self.wfile.write(b"250 ok\r\n")
            elif verb == b"DATA":
                self.wfile.write(b"354 end with a dot\r\n")
                content = []
                while line := self.rfile.readline(2048):
                    if line == b".\r\n":
                        self.server.inbox.put((envelope, b"".join(content)))
                        self.wfile.write(b"250 stored\r\n")
                        break
                    content.append(line[1:] if line.startswith(b"..") else line)
            elif verb == b"QUIT":
                self.wfile.write(b"221 bye\r\n")
                return
            else:
                self.wfile.write(b"502 unsupported\r\n")


class OnlyError(logging.Filter):
    def filter(self, record):
        return record.levelno == logging.ERROR


class JsonFormatter(logging.Formatter):
    def format(self, record):
        return json.dumps({"logger": record.name, "level": record.levelname, "message": record.getMessage()})


def detach(logger, *handlers):
    for handler in handlers:
        logger.removeHandler(handler)
        handler.close()


def observe():
    checks = []

    def check(name, actual, expected, inputs, operation):
        if actual != expected:
            raise AssertionError((name, actual, expected))
        checks.append(dict(name=name, input=inputs, operation=operation, actual=actual,
                           expected=expected, passed=True))

    root = logging.getLogger()
    check("initial root warning threshold", [root.level, bool(root.handlers)], [30, False],
          "fresh Python process", "Inspect root logger before configuration")
    check("standard levels numeric order", [logging.NOTSET, logging.DEBUG, logging.INFO, logging.WARNING,
          logging.ERROR, logging.CRITICAL], [0, 10, 20, 30, 40, 50], "six standard constants",
          "Read each actual numeric value")

    first, replacement = io.StringIO(), io.StringIO()
    with redirect_stderr(first):
        logging.basicConfig(level=logging.DEBUG, format="%(levelname)s|%(message)s")
        first_handler, = root.handlers
        check("default StreamHandler uses current stderr", first_handler.stream is first, True,
              "basicConfig without stream or filename", "Compare the created handler's stream")
        logging.basicConfig(level=logging.CRITICAL, stream=replacement)
        logging.debug("debug sample")
        logging.info("info sample")
        logging.warning("warning sample")
        logging.error("error sample")
        logging.critical("critical sample")
    expected_levels = ["DEBUG|debug sample", "INFO|info sample", "WARNING|warning sample", "ERROR|error sample",
                       "CRITICAL|critical sample"]
    check("root methods emit five actual level messages", first.getvalue().splitlines(), expected_levels,
          "five methods at root DEBUG", "Capture actual stream text in order")
    check("second basicConfig leaves root handlers and level", [root.handlers == [first_handler], root.level, replacement.getvalue()],
          [True, 10, ""], "second call without force", "Verify configured handler, threshold, and unused stream")
    logging.basicConfig(level=logging.WARNING, stream=replacement, format="%(message)s", force=True)
    logging.info("hidden")
    logging.warning("visible")
    check("force replaces root configuration", [first_handler not in root.handlers, root.level, replacement.getvalue()],
          [True, 30, "visible\n"], "force=True and WARNING", "Reconfigure and emit INFO then WARNING")

    all_levels = io.StringIO()
    logging.basicConfig(level=logging.NOTSET, stream=all_levels, format="%(message)s", force=True)
    logging.debug("root permits DEBUG")
    check("root NOTSET permits DEBUG", [root.level, all_levels.getvalue()], [0, "root permits DEBUG\n"],
          "root NOTSET and unfiltered handler", "Emit DEBUG and verify the actual output")

    parent = logging.getLogger("harbor")
    child = logging.getLogger("harbor.sensor")
    parent.setLevel(logging.INFO)
    check("named logger identity and NOTSET inheritance", [child is logging.getLogger("harbor.sensor"),
          child.level, child.getEffectiveLevel()], [True, 0, 20], "named child and parent INFO",
          "Resolve a repeated name and inspect effective threshold")
    received = io.StringIO()
    sink = logging.StreamHandler(received)
    parent.addHandler(sink)
    parent.propagate = False
    child.setLevel(logging.DEBUG)
    child.debug("forwarded debug")
    child.propagate = False
    child.debug("isolated debug")
    check("ancestor logger threshold is not reapplied on propagation", received.getvalue(), "forwarded debug\n",
          "child DEBUG, parent INFO, parent handler NOTSET", "Observe first record with propagation, then disable propagation")
    detach(parent, sink)
    parent.propagate = True
    child.propagate = True

    exact_output = io.StringIO()
    logger = logging.getLogger("workbench")
    logger.propagate = False
    logger.setLevel(logging.DEBUG)
    sink = logging.StreamHandler(exact_output)
    exact = OnlyError()
    sink.addFilter(exact)
    logger.addHandler(sink)
    logger.warning("ignored warning")
    logger.error("selected error")
    logger.critical("ignored critical")
    check("exact ERROR filter differs from threshold", exact_output.getvalue(), "selected error\n",
          "WARNING, ERROR, CRITICAL", "Filter on record.levelno equality at the handler")
    sink.removeFilter(exact)
    logger.addFilter(exact)
    logger.critical("ignored by logger filter")
    logger.error("selected by logger filter")
    check("origin logger can filter exact ERROR", exact_output.getvalue().splitlines(),
          ["selected error", "selected by logger filter"], "replace handler filter with a logger filter",
          "Filter the originating logger and verify it accepts only ERROR")
    logger.removeFilter(exact)
    detach(logger, sink)

    allowed = io.StringIO()
    sink = logging.StreamHandler(allowed)
    named = logging.Filter("workbench.sensor")
    logger.addHandler(sink)
    logger.addFilter(named)
    logger.info("origin rejected")
    sensor = logging.getLogger("workbench.sensor")
    sensor.info("descendant passes ancestor logger filter")
    sink.addFilter(named)
    logging.getLogger("workbench.other").info("wrong handler prefix")
    sensor.info("handler prefix accepted")
    check("logger filter and handler filter have distinct scope", allowed.getvalue().splitlines(),
          ["descendant passes ancestor logger filter", "handler prefix accepted"], "logger and handler filters",
          "Compare direct and propagated records before and after filtering at the handler")
    logger.removeFilter(named)
    detach(logger, sink)

    record = logging.LogRecord("workbench", logging.INFO, "sample.py", 27, "cargo %s", ("A",), None, "inspect")
    record.created = 1704067200
    formatter = logging.Formatter("%(asctime)s|%(levelname)s|%(message)s|%(name)s|%(filename)s|%(lineno)d|%(funcName)s",
                                  datefmt="%Y-%m-%dT%H:%M:%S")
    formatter.converter = time.gmtime
    expected_fields = ["2024-01-01T00:00:00", "INFO", "cargo A", "workbench", "sample.py", "27", "inspect"]
    for index, field in enumerate(("asctime", "levelname", "message", "name", "filename", "lineno", "funcName")):
        check("formatter " + field, formatter.format(record).split("|")[index], expected_fields[index],
              "one fixed LogRecord with UTC datefmt", "Format and compare the named output field")
    check("structured output with explicit JSON formatter", json.loads(JsonFormatter().format(record)),
          {"logger": "workbench", "level": "INFO", "message": "cargo A"}, "same owned LogRecord",
          "Encode and parse the record as JSON")

    stamp_capture = io.StringIO()
    logging.basicConfig(stream=stamp_capture, level=logging.INFO, format="%(asctime)s|%(message)s",
                        datefmt="%Y/%m/%d", force=True)
    root.handlers[0].formatter.converter = time.gmtime
    root.handle(record)
    check("basicConfig datefmt applied to handler", stamp_capture.getvalue(), "2024/01/01|cargo A\n",
          "fixed UTC record and custom datefmt", "Send the record through the configured root handler")

    with TemporaryDirectory(prefix="mbsky-logging-") as directory:
        work = Path(directory)
        file = work / "app.log"
        file.write_text("old\n", encoding="utf-8")
        logging.basicConfig(filename=file, encoding="utf-8", filemode="w", level=logging.INFO,
                            format="%(name)s|%(message)s", force=True)
        logging.getLogger("harbor.entry").info("清点完成")
        detach(root, *root.handlers)
        check("basicConfig filemode w replaces and encodes UTF-8", file.read_text(encoding="utf-8"),
              "harbor.entry|清点完成\n", "pre-existing file and force configuration",
              "Write a UTF-8 message and re-open the closed log file")
        logging.basicConfig(filename=file, encoding="utf-8", level=logging.INFO, format="%(message)s")
        logging.info("附记")
        detach(root, *root.handlers)
        check("basicConfig default file mode appends", file.read_text(encoding="utf-8"),
              "harbor.entry|清点完成\n附记\n", "existing log with no filemode option", "Write a second record and compare both lines")

        console = io.StringIO()
        stream = logging.StreamHandler(console)
        stream.setLevel(logging.WARNING)
        disk_path = work / "details.log"
        disk = logging.FileHandler(disk_path, encoding="utf-8")
        disk.setLevel(logging.DEBUG)
        for handler in (stream, disk):
            handler.setFormatter(logging.Formatter("%(levelname)s|%(message)s"))
            logger.addHandler(handler)
        logger.debug("检查坐标")
        logger.warning("水位上升")
        detach(logger, stream, disk)
        check("DEBUG file and WARNING console route differently",
              [disk_path.read_text(encoding="utf-8").splitlines(), console.getvalue().splitlines()],
              [["DEBUG|检查坐标", "WARNING|水位上升"], ["WARNING|水位上升"]],
              "two handlers with distinct thresholds", "Write two records, close handlers, and compare actual destinations")

        size_path = work / "size.log"
        rotating = RotatingFileHandler(size_path, maxBytes=32, backupCount=3, encoding="utf-8")
        logger.addHandler(rotating)
        lines = ["record-" + str(i) + "-" * 14 for i in range(5)]
        for line in lines:
            logger.info(line)
        detach(logger, rotating)
        actual = {path.name: path.read_text(encoding="utf-8").strip() for path in work.glob("size.log*")}
        check("size rotation keeps active file plus three newest backups", actual,
              {"size.log": lines[4], "size.log.1": lines[3], "size.log.2": lines[2], "size.log.3": lines[1]},
              "five ASCII records with maxBytes=32 and backupCount=3", "Trigger several rollovers and inspect retained contents")

        time_path = work / "timed.log"
        timed = TimedRotatingFileHandler(time_path, when="S", interval=1, backupCount=1, utc=True, encoding="utf-8")
        logger.addHandler(timed)
        timed.rolloverAt = int(time.time()) + 60
        logger.info("before boundary")
        timed.rolloverAt = 1704067201
        logger.info("after boundary")
        detach(logger, timed)
        backup, = work.glob("timed.log.*")
        check("timed rotation occurs on emit at elapsed boundary",
              [backup.name, backup.read_text(encoding="utf-8").strip(), time_path.read_text(encoding="utf-8").strip()],
              ["timed.log.2024-01-01_00-00-00", "before boundary", "after boundary"],
              "UTC boundary explicitly set in the past after first emission", "Emit again and inspect archived and active content")

    with socketserver.TCPServer(("127.0.0.1", 0), LocalMail) as server:
        server.inbox = Queue()
        worker = Thread(target=server.serve_forever, daemon=True)
        worker.start()
        mail = SMTPHandler(server.server_address, "sender@example.invalid", ["sink@example.invalid"], "Local log test", timeout=4)
        mail.setLevel(logging.ERROR)
        logger.addHandler(mail)
        try:
            logger.warning("warning stays local")
            logger.error("port alarm")
            envelope, raw = server.inbox.get(timeout=4)
        finally:
            detach(logger, mail)
            server.shutdown()
            worker.join(timeout=4)
    parsed = BytesParser(policy=policy.default).parsebytes(raw)
    check("SMTPHandler sends actual local envelope and error body",
          [envelope, parsed["Subject"], parsed.get_content().strip(), server.inbox.empty(), worker.is_alive()],
          [["mail FROM:<sender@example.invalid>", "rcpt TO:<sink@example.invalid>"], "Local log test",
           "port alarm", True, False], "WARNING and ERROR on an owned loopback handler",
          "Capture actual SMTP delivery, decode its message, and stop the local peer")
    return checks


if __name__ == "__main__":
    print(json.dumps(observe(), ensure_ascii=True, indent=2))
运行本章核心实例

所需环境:CPython logging levels, separate handlers, rollover and actual SMTP loopback

当前源码 SHA256:16a4fdf7b14a7f8389a4ea618853bcdff14d72906098e9331ce6866886a3fa1a

下载本站示例源码

当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。

常见错误与边界

  • 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。

练习与解答

使用本站实例修改一个条件,先写下预期,再实际运行。

展开参考解答

比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。

规范与官方依据