"""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 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython logging levels, separate handlers, rollover and actual SMTP loopback
入口文件:projects/python-lab/python-logging.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
python-logging.py,或下载右侧课程工程包。 - 确认本地已准备 CPython logging levels, separate handlers, rollover and actual SMTP loopback。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a295.zip
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip