TL;DR
- A log line goes missing for one of six reasons, and only one of them is the disk: two processes rolling the same file rename it out from under each other, a buffer holds the last second of records when the process is killed, a queue drops what does not fit or loses it at exit, and a slow sink blocks the caller. Four writers that rotate one file kept 526 of 800 records on disk with the standard handler, and dropped 7 more while rolling.
- Durability is the expensive part: one fsync per record costs 5.69 ms on the log mount measured here, which caps a single thread at 175.7 records a second, against 12,562 for a handler that only flushes.
- The fix is two guards and one rule: roll under a lock and follow the file when someone else moves them, hand the record to a queue that counts its drops, and keep the write off the thread that answers requests. Measured: 800 of 800 records kept, 0 dropped, and a queue that took 1.8 ms where the inline call took 1,089 ms.
What this runbook covers
- What was measured, on what, and what was not
- Six ways a log line disappears
- What one log call costs
- The rotation race, measured with four writers
- What survives a kill
- The handler blocks whatever calls it
- A full queue drops loudly, a hasty exit drops silently
- logguard: the lock, the follow, the count
- The production runbook
- What to put on a dashboard
- Frequently asked questions
- What was verified, and what is out of scope
- Keep reading on TechBobby
1. What was measured, on what, and what was not
Logging fails quietly. Nothing raises, the request returns, the service stays up – and the line that would have explained the incident is not in the file. Every number below came from running that failure on this machine and reading the answer out of a file, a queue, a clock or /proc. The probes write JSON, the article renders its figures from that JSON, and a token that no probe wrote stops the build, so a number cannot be typed into the page by hand.
| Item | Measured value | How it was read |
|---|---|---|
| Kernel | 6.12.8+ on x86_64 | platform.release() |
| CPU | Intel(R) Xeon(R) Platinum 8488C, 2 vCPUs | /proc/cpuinfo |
| Memory | 1,522,164 KiB total, 608,540 KiB available | /proc/meminfo |
| Python | 3.12.16, CPython | platform.python_version() |
| Log mount | virtiofs at /workspace, block size 1,048,576 bytes | /proc/mounts, os.stat() |
| Second mount | tmpfs at /tmp, block size 4,096 bytes | the same, for the comparison in section 5 |
| Default stream buffer | 8,192 bytes | io.DEFAULT_BUFFER_SIZE |
| write() on the log mount | 0.065 ms per call | 200 writes of 200 bytes, no flush |
| write() + fsync, log mount | 5.24 ms per call | 200 pairs, p95 5.84 ms |
| write() + fsync, second mount | 0.001 ms per call | 200 pairs on tmpfs |
| Clock resolution | 1 ns | time.get_clock_info('perf_counter') |
results/00_env.json.The log mount matters more than the CPU here. It is virtiofs, a network filesystem, and its block size is 1,048,576 bytes. That block size is also the buffer Python gives every file opened on it with default buffering, and it is worth being exact about why: io.DEFAULT_BUFFER_SIZE is 8,192 bytes, and CPython uses the mount’s st_blksize in place of it whenever that value is greater than one – it does not take the larger of the two. On this mount the replacement is a 1 MiB buffer, and on the tmpfs mount it is 4,096 bytes, which is smaller than the default it replaced. Section 5 measures the buffer instead of arguing from the rule. The 1 MiB buffer is what makes section 5’s crash result as stark as it is, and the price of a metadata round trip is what makes section 8’s guard look expensive on this mount and free on the other. Both are measured, and both are properties of where the log lives rather than of the code.
The probes are ordinary programs: standard library only, no dependencies, each one writing a single JSON record that the page then reads. One child process writes with logging and gets killed; four child processes rotate one file; one coroutine logs while another measures how late the event loop is. Each section prints the part of its file that produced the number it is talking about – the constants, the children and the functions below – and the probe’s main(), which only calls those functions and writes the record, stays in the file. The one exception is the timing harness behind section 8’s per-record costs, which that section describes instead of printing.
Five things in the shared file are needed to reproduce any of it, so they are printed here rather than assumed: the two record shapes the probes write (the line length a table quotes is measured from the same template, because a record with a three-digit index is longer than one with a one-digit index), the child that section 5 kills, the worker that section 4 starts four of, the helper that measures a record’s size, and the three helpers that read a log directory back.
from __future__ import annotations
import pathlib
import statistics
PAYLOAD = "y" * 104
LINE = "record {index} " + PAYLOAD + "\n"
WORKER_LINE = "worker {worker} record {index} " + "z" * 104 + "\n"
CHILD = '''
import logging, os, sys, time
path, mode, total, mark_path = sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4]
logger = logging.getLogger("app")
logger.setLevel(logging.INFO)
logger.propagate = False
stream = open(path, "ab", buffering=0 if mode == "unbuffered" else -1)
class Handler(logging.Handler):
def emit(self, record):
stream.write((record.getMessage() + "\\n").encode())
if mode == "fsync":
stream.flush()
os.fsync(stream.fileno())
logger.addHandler(Handler())
for index in range(total):
logger.info("record %d %s", index, "y" * 104)
open(mark_path, "w").close()
while True: # the parent kills this process; nothing else runs
time.sleep(0.01)
'''
ROTATOR = '''
import logging, logging.handlers, os, sys, time
path, worker, total, max_bytes, backups, start = (sys.argv[1], int(sys.argv[2]), int(
sys.argv[3]), int(sys.argv[4]), int(sys.argv[5]), float(sys.argv[6]))
handler = logging.handlers.RotatingFileHandler(path, maxBytes=max_bytes, backupCount=backups)
handler.setFormatter(logging.Formatter("%(message)s"))
logger = logging.getLogger("worker-%d" % worker)
logger.setLevel(logging.INFO)
logger.propagate = False
logger.addHandler(handler)
while time.time() < start: # every worker starts inside the same millisecond
pass
for index in range(total):
logger.info("worker %d record %d %s", worker, index, "z" * 104)
'''
def line_bytes(template: str, records: int, workers: int = 1) -> dict:
"""The exact size of the records a probe writes, measured from its own template.
A line length typed into the prose is wrong as soon as an index grows a
digit: ``record 999`` is two bytes longer than ``record 0``, and the mean is
what a buffer division needs. So each probe formats the records it is about
to write and records the range and the mean instead of quoting a constant.
"""
sizes = [len(template.format(worker=worker, index=index).encode())
for worker in range(workers) for index in range(records)]
return {"min": min(sizes), "max": max(sizes),
"mean": round(sum(sizes) / len(sizes), 2), "total": sum(sizes)}
def summary(samples: list[float]) -> dict:
"""Median, p95, min and max of a list of samples, in the sample's unit."""
ordered = sorted(samples)
return {
"n": len(ordered),
"median": round(statistics.median(ordered), 4),
"p95": round(ordered[min(len(ordered) - 1, int(len(ordered) * 0.95))], 4),
"min": round(ordered[0], 4),
"max": round(ordered[-1], 4),
}
def read_lines(path: pathlib.Path) -> list[str]:
"""Every complete line of a log file, or nothing if it was never created."""
if not path.exists():
return []
return path.read_text(errors="replace").splitlines()
def tree_files(directory: pathlib.Path) -> list[dict]:
"""Name, size and line count of every file a rotation left behind."""
return [{"name": child.name, "bytes": child.stat().st_size,
"lines": len(read_lines(child))}
for child in sorted(directory.iterdir()) if child.is_file()
and not child.name.endswith(".lock")]
Everything a probe needs to describe its host comes from environment() and mount_of(), which is why Table 1 is a record of what the kernel said rather than a specification anyone assumed.
from __future__ import annotations
import io
import os
import pathlib
import platform
import sys
import time
def mount_of(path: pathlib.Path) -> dict:
"""The filesystem type, block size and mount point that hold ``path``."""
stat = os.stat(path)
resolved = str(path.resolve())
fstype, mountpoint = "unknown", ""
for line in pathlib.Path("/proc/mounts").read_text().splitlines():
parts = line.split()
if len(parts) < 3:
continue
point = parts[1].replace("\\040", " ")
if resolved == point or resolved.startswith(point.rstrip("/") + "/"):
if len(point) >= len(mountpoint):
fstype, mountpoint = parts[2], point
return {"fstype": fstype, "mount": mountpoint, "st_blksize": stat.st_blksize,
"st_dev": stat.st_dev}
def environment() -> dict:
"""The facts about this host that the article quotes, each read, not assumed."""
cpu = [line.split(":", 1)[1].strip()
for line in pathlib.Path("/proc/cpuinfo").read_text().splitlines()
if line.startswith("model name")]
mem = {}
for line in pathlib.Path("/proc/meminfo").read_text().splitlines():
key, value = line.split(":", 1)
mem[key] = value.strip()
return {
"kernel": platform.release(),
"machine": platform.machine(),
"python": platform.python_version(),
"implementation": platform.python_implementation(),
"cpu_model": cpu[0] if cpu else "unknown",
"cpu_count": os.cpu_count(),
"mem_total_kib": int(mem["MemTotal"].split()[0]),
"mem_available_kib": int(mem["MemAvailable"].split()[0]),
"clock_resolution_ns": round(time.get_clock_info("perf_counter").resolution * 1e9),
"open_fds": len(list(pathlib.Path("/proc/self/fd").iterdir())),
"default_buffer": io.DEFAULT_BUFFER_SIZE,
"python_executable": sys.executable,
}
Out of scope: Syslog, journald, the Docker and Kubernetes log drivers, cloud agents, structured JSON formatters, the cost of tracing, Windows event logs, macOS unified logging, and the performance of any particular storage appliance are out of scope. So is multi-machine log shipping: everything here is one host, one path, and processes that share a filesystem namespace. Section 8 stays on the guards that stop a line from disappearing; what to do once lines are cheap – sampling, structured fields, shipping them off the host – is a different article.
2. Six ways a log line disappears
Six failures wear the same symptom – a line the application definitely emitted is not in the file – and each needs a different fix. The table is the one this article works from: what the operator sees, what is actually happening, the measurement that names it, and the section that measures it.
| Shape | What you see | The mechanism | Measured evidence | Section |
|---|---|---|---|---|
| rotation race | Whole runs of lines missing around a rollover, and tracebacks on stderr | Two processes roll the same path: each renames the file the other still holds, and the loser’s rename raises FileNotFoundError inside emit | 526 of 800 records kept, 7 dropped while rolling | Section 4 |
| buffer | Everything since the last flush is gone after a kill | The file object holds the records in memory; a process that dies without flushing never hands them to the kernel | 1,000 of 1,000 records lost on the virtiofs mount, 20 on tmpfs | Section 5 |
| durability cost | Throughput collapses when fsync is added | A write is durable only after fsync, and each one waits for the storage | 5.69 ms per record, 175.7 records a second | Section 3 |
| blocked caller | Request latency spikes with no CPU use, or the whole loop stalls | The handler runs on the thread that called it, and a slow sink is time spent not serving | 1,021 ms for 200 records, one loop stall of 1,021 ms | Section 6 |
| full queue | stderr fills with --- Logging error ---, the log does not | QueueHandler uses put_nowait, so a full queue raises inside the handler and the record is dropped through handleError | 2 of 500 delivered, 398 refused at the put, 100 still in the queue when the burst ended | Section 7 |
| hasty exit | Nothing at all in the file, and no error anywhere | The listener thread has not written what the queue still holds when the interpreter stops, and stop() was never called | 499 of 500 records lost with exit code 0 | Section 7 |
Only the first row involves two processes; only the second and third involve durability; only the last two involve a queue. That is the reason to keep them apart: an operator who sees gaps in a log file tends to add fsync, which addresses none of the other five, and an operator who sees stderr full of queue.Full tracebacks tends to grow the queue, which moves the loss rather than removing it.
One convention throughout: a difference smaller than the spread between two runs of the same probe is reported as flat, no row of a table quietly mixes one run’s numbers with another’s, and where the runs behind a row disagreed the caption says which cell is which.
3. What one log call costs
The cost of a log call is the cost of whatever its handler does, and the four sinks below differ by more than four orders of magnitude. They are the same call – logger.info("record %d %s", index, payload) – against a logger that rejects the level, a file handler, the same handler with an fsync, and a handler whose sink takes five milliseconds on purpose. 1,000 records per trial, five trials, one thread.
from __future__ import annotations
import logging
import os
import time
import common
def build(sink: str, path) -> tuple[logging.Logger, object]:
"""A logger and its handler, configured the way the name says."""
logger = logging.getLogger(f"probe-01-{sink}")
logger.setLevel(logging.INFO)
logger.propagate = False
logger.handlers.clear()
if sink == "filtered":
logger.setLevel(logging.ERROR) # every info() below is rejected
return logger, None
if sink in ("file", "fsync"):
handler = logging.FileHandler(path)
if sink == "fsync":
inner = handler
class Fsync(logging.FileHandler):
def emit(self, record):
inner.emit(record)
os.fsync(inner.stream.fileno())
handler = Fsync(path)
logger.addHandler(handler)
return logger, handler
if sink == "slow":
# A sink that takes 5 ms: the shape of an HTTP handler, a syslog socket
# whose reader is behind, or a disk that has to spin up.
class Slow(logging.Handler):
def emit(self, record):
self.format(record)
time.sleep(0.005)
handler = Slow()
logger.addHandler(handler)
return logger, handler
raise SystemExit(f"unknown sink {sink}")
def per_record_ms(logger: logging.Logger, records: int) -> list[float]:
samples = []
for index in range(records):
start = time.perf_counter()
logger.info("record %d %s", index, common.PAYLOAD)
samples.append((time.perf_counter() - start) * 1000)
return samples
A record the logger rejects costs 0.1 microseconds: the level check and nothing else. A file handler costs 79.6 microseconds per record, because StreamHandler.emit flushes after every line, so each record is one write syscall and the ceiling is 12,562 records a second. Add an fsync and the same call costs 5.69 milliseconds – 175.7 records a second – which is the entire throughput budget of an async service spent on one line.
| Sink | Median per record | Records per second | What it measures |
|---|---|---|---|
| level rejected | 0.1 us | not applicable | the guard around the call |
| file handler | 79.6 us | 12,562 | write plus flush per record |
| file handler + fsync | 5.69 ms | 175.7 | durable per record |
| slow sink (5 ms by construction) | 5.10 ms | 195.9 | a remote or contended sink |
Formatting is the cheap part, and the only part a disabled level can avoid. An f-string argument costs 0.266 microseconds even when the record is thrown away, a %-style template costs 0.166 microseconds, and building the string itself accounts for 0.162 microseconds of it. The difference is a tenth of a microsecond per call, which matters only in a loop that logs a million times a second – while the fsync above it bites at a few hundred records a second. Optimising the formatter is a rounding error next to choosing the sink.
What the fast row does not promise: The file handler’s number is a flush, not a durable write: it hands the bytes to the kernel and returns, so the record survives the process and not the machine. The gap between that row and the fsync row – 79.6 microseconds against 5.69 milliseconds – is what a power cut costs, and it is the only difference between the two rows.
4. The rotation race, measured with four writers
The standard advice for a large log file is a rotating handler, and the standard rotating handler is written for one writer. Each process keeps its own open file, checks its own stream’s position, and rolls by renaming the path to app.log.1, shifting the older backups down, and opening the path again. With two processes on one path, each of those steps lands on a file the other process is holding: the second process to roll renames a path that no longer exists, the rename raises FileNotFoundError inside emit, logging prints a traceback and drops that record – and the loser still writes to a file that has already been unlinked from the chain.
The probe below starts four processes that all begin inside the same millisecond, writes 300 records of 123 to 125 bytes from each, and then counts what is on disk. It also parses every surviving line to see which writer it came from, because retention deletes old lines by design and an aggregate count cannot tell a design decision from a defect.
from __future__ import annotations
import pathlib
import re
import subprocess
import sys
import time
import common
RECORDS = 300
WORKERS = 4
MAX_BYTES = 16384
BACKUPS = 4
TRIALS = 3
TAIL = 50
LINE = re.compile(r"^worker (\d+) record (\d+) ")
def parse(directory: pathlib.Path) -> dict[int, set[int]]:
"""Every (writer, index) pair that is in any file the rotation left."""
seen: dict[int, set[int]] = {}
for item in common.tree_files(directory):
for line in common.read_lines(directory / item["name"]):
match = LINE.match(line)
if match:
seen.setdefault(int(match.group(1)), set()).add(int(match.group(2)))
return seen
def run(directory: pathlib.Path, workers: int, records: int, max_bytes: int,
backups: int) -> dict:
"""Start ``workers`` children on one path and report what survived."""
path = directory / "app.log"
start = time.time() + 0.5
children = [subprocess.Popen(
[sys.executable, "-c", common.ROTATOR, str(path), str(worker), str(records),
str(max_bytes), str(backups), str(start)],
stderr=subprocess.PIPE, text=True) for worker in range(workers)]
dropped = 0
rollover_missing = 0
for child in children:
_, stderr = child.communicate(timeout=120)
dropped += stderr.count("--- Logging error ---")
rollover_missing += stderr.count("FileNotFoundError")
files = common.tree_files(directory)
lines = [line for item in files for line in common.read_lines(directory / item["name"])]
seen = parse(directory)
tail_present = []
newest_present = []
for worker in range(workers):
indices = seen.get(worker, set())
last = range(max(0, records - TAIL), records)
tail_present.append(sum(1 for index in last if index in indices))
newest_present.append((records - 1) in indices)
written = workers * records
sizes = common.line_bytes(common.WORKER_LINE, records, workers)
return {
"workers": workers,
"records_each": records,
"written": written,
"line_bytes": sizes,
"written_bytes": sizes["total"],
"max_bytes": max_bytes,
"backups": backups,
"kept_lines": len(lines),
"distinct_lines_kept": len({line for line in lines}),
"dropped_at_handler": dropped,
"rollover_file_not_found": rollover_missing,
"writers_with_newest_missing": newest_present.count(False),
"writers_with_full_tail": tail_present.count(TAIL),
"tail_present_of": TAIL * workers,
"tail_present": sum(tail_present),
"files": [item["name"] for item in files],
"file_count": len([item for item in files if not item["name"].endswith(".lock")]),
"total_bytes": sum(item["bytes"] for item in files),
}
Three configurations separate the two effects. The first writes through a handler with no rotation at all, which is a control: if appending itself were unsafe across processes, every configuration would lose lines. The second rotates from a single writer, which shows what the retention settings alone keep. The third is the one most services ship.
| Configuration | Written | Kept on disk | Dropped at the handler | Newest 50 of each writer | Files left |
|---|---|---|---|---|---|
| 1,200 written, no rotation | 1,200 | 1,200 | 0 | 200 of 200 | 1 |
| one writer, rotating | 1,200 | 545 | 0 | 50 of 50 | 5 |
| four writers, rotating (trial 1) | 1,200 | 397 | 8 | 150 of 200 | 4 |
| four writers, rotating (trial 2) | 1,200 | 531 | 6 | 150 of 200 | 5 |
| four writers, rotating (trial 3) | 1,200 | 526 | 12 | 148 of 200 | 5 |
Two facts come out of that table. Appending is safe: 1,200 records from four processes all arrived, in one file, with nothing dropped, because a line written with O_APPEND is placed atomically as long as it is a single small write. And retention is a budget, not a guarantee: one writer kept 545 of the 1,200 lines it wrote – 68,325 bytes of the 81,920-byte budget, with no errors – because deleting the oldest file is what rotation is for. So a page that says “four writers lost most of the lines” would be telling only half the story.
The half it would be missing is the tail. The newest records of each writer are the ones that must survive a race, because they are the ones an operator reads after an incident: in a single-writer file they are always in app.log, and in a race they are the first thing a competing rollover throws away. In the four-writer trials 150, 150 and 148 of the 200 newest records were still there, against 50 of 50 for one writer; and 8, 6 and 12 records never reached a file at all, each with a traceback on stderr.
That configuration was deliberately tight, so the next table gives the race room: 32,768 bytes with 3 backups is a retention budget of 131,072 bytes for 99,560 bytes of records, so nothing has to be deleted for the four writers to fit. Anything missing there is a defect and nothing else. The first row is the standard handler, the second is the one in section 8.
Table 5 comes from a second probe, and the half of it that runs the four writers is printed here: the child every worker runs, the budget all of them are given, and the counting that decides what survived. Its other half – the timers behind section 8’s per-record costs – is described in that section rather than printed.
from __future__ import annotations
import pathlib
import re
import subprocess
import sys
import time
import common
WORKER_CHILD = '''
import logging, logging.handlers, sys, time
sys.path.insert(0, sys.argv[1])
from logguard import RotatingFileHandler
kind, path, worker, total, max_bytes, backups, start = (sys.argv[2], sys.argv[3],
int(sys.argv[4]), int(sys.argv[5]), int(sys.argv[6]), int(sys.argv[7]),
float(sys.argv[8]))
handler = (RotatingFileHandler if kind == "guard"
else logging.handlers.RotatingFileHandler)(path, maxBytes=max_bytes,
backupCount=backups)
handler.setFormatter(logging.Formatter("%(message)s"))
logger = logging.getLogger("worker-%d" % worker)
logger.setLevel(logging.INFO)
logger.propagate = False
logger.addHandler(handler)
while time.time() < start:
pass
for index in range(total):
logger.info("worker %d record %d %s", worker, index, "z" * 104)
'''
WORKERS = 4
RECORDS = 200
MAX_BYTES = 32768
BACKUPS = 3
TAIL = 50
LINE = re.compile(r"^worker (\d+) record (\d+) ")
ROOT = pathlib.Path(__file__).resolve().parents[1]
def one_trial(directory: pathlib.Path, kind: str) -> dict:
for child in directory.iterdir():
child.unlink()
path = directory / "app.log"
start = time.time() + 0.5
children = [subprocess.Popen(
[sys.executable, "-c", WORKER_CHILD, str(ROOT / "module"), kind, str(path),
str(worker), str(RECORDS), str(MAX_BYTES), str(BACKUPS), str(start)],
stderr=subprocess.PIPE, text=True) for worker in range(WORKERS)]
dropped = 0
rollover_errors = 0
for child in children:
_, stderr = child.communicate(timeout=180)
dropped += stderr.count("--- Logging error ---")
rollover_errors += stderr.count("FileNotFoundError")
files = common.tree_files(directory)
present: dict[int, set[int]] = {}
for item in files:
for line in common.read_lines(directory / item["name"]):
match = LINE.match(line)
if match:
present.setdefault(int(match.group(1)), set()).add(int(match.group(2)))
tails = {worker: sum(1 for index in range(RECORDS - TAIL, RECORDS)
if index in present.get(worker, set()))
for worker in range(WORKERS)}
return {
"kind": kind,
"written": WORKERS * RECORDS,
"kept_lines": sum(item["lines"] for item in files),
"writers_present": len(present),
"writers_with_full_tail": sum(1 for value in tails.values() if value == TAIL),
"tail_records_of": WORKERS * TAIL,
"tail_records_kept": sum(tails.values()),
"worst_writer_tail": min(tails.values()),
"dropped_at_handler": dropped,
"rollover_file_not_found": rollover_errors,
"files": len([item for item in files if not item["name"].endswith(".lock")]),
"bytes": sum(item["bytes"] for item in files),
}
| Handler | Records kept | Dropped at the handler | Files left | Bytes kept |
|---|---|---|---|---|
standard RotatingFileHandler | 526 of 800 | 7 | 3, 4, 4 | 65,620 |
locked rollover (logguard) | 800 of 800 | 0 | 4, 4, 4 | 99,560 |
Reading the file count, not the line count: The standard handler kept 526, 530 and 531 of the 800 lines it was given, and the file count shows the mechanism rather than one number: 3, 4 and 4 files where the configuration allows four. Three files means a whole generation was named over by a competing writer. Four files with lines still missing means the rename replaced a file another process had just filled, so the chain never shrank and the records went anyway. Either way it is a rename, not a delete by retention – retention takes the oldest file and only the oldest.
The drift between a single writer and four is not a rare corner: a pre-forked WSGI server, a Gunicorn worker pool, a Celery worker with concurrency above one, or any service started with more than one replica on the same volume produces it. The usual advice – configure rotation, forget about it – is advice for one process. Section 8’s handler is the smallest change that makes the same configuration safe for the others.
One more observation from the same probe, because it shapes the fix: the writes themselves are never interleaved within a line. Every trial in the no-rotation row produced lines of 123 to 125 bytes with no torn or merged lines, and the same is true of the rotating rows. What the race breaks is not the write, it is the name: which file the path points at, and which file each process believes it is writing to.
5. What survives a kill
Whether a kill costs records depends on one decision: does the handler flush after every record? Python’s own FileHandler does, through StreamHandler.emit, which is what the 79.6 microseconds of Table 3 buys. A handler that batches, which is the first thing anyone writes when that cost appears in a profile, gives the flush up and keeps the bytes in the process. The probe below makes the difference exact: a child logs a fixed number of records, touches a marker file, and then sleeps, so the parent knows precisely how many records were logged when it sends SIGKILL.
from __future__ import annotations
import io
import os
import pathlib
import signal
import subprocess
import sys
import time
import common
TRIALS = 3
RECORDS = 1000
EXIT_CHILD = '''
import logging, os, signal, sys
path, how, total = sys.argv[1], sys.argv[2], int(sys.argv[3])
stream = open(path, "ab") # the same buffered stream the other child in this probe uses
class Batch(logging.Handler):
"""A batching handler: it writes to the stream and never flushes it."""
def __init__(self, stream):
super().__init__()
self.stream = stream
def emit(self, record):
self.stream.write((record.getMessage() + "\\n").encode())
logger = logging.getLogger("app")
logger.setLevel(logging.INFO)
logger.propagate = False
logger.addHandler(Batch(stream))
for index in range(total):
logger.info("record %d %s", index, "y" * 104)
if how == "sys.exit":
sys.exit(0)
elif how == "os._exit":
os._exit(0)
else:
os.kill(os.getpid(), signal.SIGKILL)
'''
def one(directory: pathlib.Path, mode: str, trial: int) -> dict:
path = directory / f"{mode}-{trial}.log"
marker = directory / f"{mode}-{trial}.mark"
for candidate in (path, marker):
candidate.unlink(missing_ok=True)
child = subprocess.Popen(
[sys.executable, "-c", common.CHILD, str(path), mode, str(RECORDS), str(marker)],
stderr=subprocess.PIPE, text=True)
deadline = time.time() + 60
while not marker.exists() and child.poll() is None and time.time() < deadline:
time.sleep(0.001)
child.send_signal(signal.SIGKILL)
_, stderr = child.communicate(timeout=30)
lines = common.read_lines(path)
size = path.stat().st_size if path.exists() else 0
marker.unlink(missing_ok=True)
return {"mode": mode, "logged": RECORDS, "on_disk": len(lines),
"lost": RECORDS - len(lines), "bytes": size,
"stopped_early": child.returncode != -signal.SIGKILL,
"child_stderr": stderr.strip()[:200]}
def buffer_probe(directory: pathlib.Path) -> dict:
"""How many bytes a file opened with default buffering here holds before writing.
That number is the buffer: it is what an unflushed record dies in. Checking it
instead of reading ``st_blksize`` is the point - the two agree on this host,
and the reader can see that they do.
"""
path = directory / "buffer-probe.log"
path.unlink(missing_ok=True)
block = b"x" * 64
stream = open(path, "ab") # buffering=-1, the default
flushed_at = 0
written = 0
try:
for _ in range(20000): # 1.28 MiB in 64-byte blocks
stream.write(block)
written += len(block)
if written % 2048 == 0: # a stat per 2 KiB keeps this quick
size = path.stat().st_size
if size:
flushed_at = size
break
finally:
stream.close()
path.unlink(missing_ok=True)
return {"st_blksize": os.stat(directory).st_blksize,
"default_buffer": io.DEFAULT_BUFFER_SIZE,
"bytes_before_first_flush": flushed_at,
"bytes_written": written}
def exits(directory: pathlib.Path, how: str, trial: int) -> dict:
"""A child that ends three different ways with the same buffered records."""
path = directory / f"exit-{how}-{trial}.log"
path.unlink(missing_ok=True)
child = subprocess.run(
[sys.executable, "-c", EXIT_CHILD, str(path), how, str(RECORDS)],
capture_output=True, text=True, timeout=120)
lines = common.read_lines(path)
path.unlink(missing_ok=True)
return {"how": how, "records": RECORDS, "on_disk": len(lines),
"lost": RECORDS - len(lines), "exit_code": child.returncode,
"child_stderr": child.stderr.strip()[:200]}
The result depends on the buffer size, and the buffer size depends on the mount. On the virtiofs mount, whose block size is 1,048,576 bytes, Python opens a 1,048,576-byte buffer, so the first 1,000 records – 115,890 bytes – fit inside it and none of them reached the file: 1,000 lost. On the tmpfs mount, whose block size is 4,096 bytes, the buffer holds at most 35 lines of the same record: 20 records were lost, the tail of the last buffer.
That buffer is measured rather than inferred, because the rule is easy to get wrong. A file opened on each mount with default buffering, written 64 bytes at a time and checked with stat(), first reaches the disk after 1,048,576 bytes on the virtiofs mount and 4,096 on tmpfs – while io.DEFAULT_BUFFER_SIZE is 8,192 on both. So the mount’s st_blksize does not have to beat the default to be used: it replaces the default whenever it is greater than one, which is why the tmpfs buffer here is smaller than DEFAULT_BUFFER_SIZE instead of equal to it.
| Mount | Buffer | Write policy | Records on disk | Lost |
|---|---|---|---|---|
| virtiofs at /workspace | 1,048,576 bytes | write per record, no buffer | 1,000 | 0 |
| virtiofs at /workspace | 1,048,576 bytes | buffered, no flush per record | 0 | 1,000 |
| virtiofs at /workspace | 1,048,576 bytes | flush plus fsync per record | 1,000 | 0 |
| tmpfs at /tmp | 4,096 bytes | write per record, no buffer | 1,000 | 0 |
| tmpfs at /tmp | 4,096 bytes | buffered, no flush per record | 980 | 20 |
| tmpfs at /tmp | 4,096 bytes | flush plus fsync per record | 1,000 | 0 |
The lesson is not “use fsync everywhere”. It is that the number of records a crash costs is a property you can compute before it happens: it is the buffer size divided by the line size, and the buffer size is whatever the mount’s st_blksize makes it. On this mount that is 1,048,576 bytes, about 9,048 lines of the 115.89-byte record this probe writes – more than nine times what the probe logged, which is why not one of its 1,000 records had reached the file when the kill arrived. For a service writing thousands of lines a second that is a few seconds of records; at a few lines a minute it is days. Writing without a buffer moves the boundary from the process to the kernel: the line survives the process and not a machine crash. Only fsync moves it to the storage.
How the process ends decides whether that buffer is written, and only two of the ways are fatal. The same 1,000 buffered records, in a child that ends three different ways, left 1,000 lines on disk after sys.exit(), 0 after os._exit(), and 0 after SIGKILL on the virtiofs mount. sys.exit() raises SystemExit, the interpreter runs its shutdown, and the buffer is flushed on the way out; os._exit() and a signal skip all of it. On the tmpfs mount the same three ended with 1,000, 980 and 980 lines: the same 20-record tail that the buffered row of Table 6 reports, because this child writes through the same buffered stream, the same records on the same 4 KiB buffer. The orchestrator and the OOM killer use the second pair.
The optimisation that creates the risk: The 79.6 microseconds of Table 3 and the 1,000 lost records of Table 6 are one decision seen from two sides: a handler that flushes per record loses nothing it logged, and a handler that batches is cheap until the process ends without flushing. A container killed by its orchestrator, a worker recycled after a timeout and an os._exit() in a forked child all end the process the same way – and a sys.exit() does not, which is why it is not on that list: it raises SystemExit, and the interpreter flushes on the way out. Batching is a reasonable choice – it is the cheapest way to keep the write off the hot path without a queue – as long as the flush is somewhere, in a timer or at shutdown, and the buffer it leaves behind is one the service can afford to lose.
6. The handler blocks whatever calls it
A handler runs on whichever thread called the logger. In a request handler that is a worker that is not serving; in a coroutine it is the entire event loop, because everything that is not a pure CPU loop is on that thread too. The probe measures the difference between calling the handler inline and handing the record to a listener thread, with a sink that takes five milliseconds – the shape of an HTTP log collector, a socket whose reader is behind, or a disk that has to be read before it can be appended to.
from __future__ import annotations
import asyncio
import logging
import logging.handlers
import os
import queue
import time
import common
RECORDS = 200
TICK = 0.002
SLOW_S = 0.005
def slow_handler() -> logging.Handler:
"""A handler whose sink costs five milliseconds, like a network handler."""
class Slow(logging.Handler):
def emit(self, record):
self.format(record)
time.sleep(SLOW_S)
return Slow()
def fsync_handler(path) -> logging.Handler:
"""A file handler that makes each record durable before it returns."""
class Fsync(logging.FileHandler):
def emit(self, record):
super().emit(record)
os.fsync(self.stream.fileno())
return Fsync(path)
def ticker(stop: asyncio.Event, lags: list[float]) -> None:
"""Record how much later than asked the loop runs a two-millisecond sleep."""
async def run() -> None:
loop = asyncio.get_running_loop()
while not stop.is_set():
start = loop.time()
await asyncio.sleep(TICK)
lags.append((loop.time() - start - TICK) * 1000)
asyncio.ensure_future(run())
async def measure(mode: str, sink: str, directory) -> dict:
logger = logging.getLogger(f"probe-04-{mode}-{sink}")
logger.setLevel(logging.INFO)
logger.propagate = False
logger.handlers.clear()
handler = slow_handler() if sink == "slow" else fsync_handler(
directory / f"{mode}-{sink}.log")
listener = None
if mode == "queued":
channel: queue.Queue = queue.Queue(maxsize=RECORDS)
logger.addHandler(logging.handlers.QueueHandler(channel))
listener = logging.handlers.QueueListener(channel, handler)
listener.start()
else:
logger.addHandler(handler)
stop = asyncio.Event()
lags: list[float] = []
ticker(stop, lags)
await asyncio.sleep(0.05)
start = time.perf_counter()
for index in range(RECORDS):
logger.info("record %d %s", index, common.PAYLOAD)
burst_ms = (time.perf_counter() - start) * 1000
# Give a queued handler the same wall clock the inline one spent, then stop.
await asyncio.sleep(max(0.0, burst_ms / 1000 if mode == "inline" else 1.0))
stop.set()
await asyncio.sleep(0.05)
lag = common.summary(lags)
if listener is not None:
listener.stop()
logger.handlers.clear()
handler.close()
return {"mode": mode, "sink": sink, "records": RECORDS, "burst_ms": round(burst_ms, 1),
"burst_per_record_ms": round(burst_ms / RECORDS, 3), "lag_ms": lag,
"lag_samples": len(lags), "lag_over_10ms": sum(1 for value in lags if value > 10)}
The measurement is a second task that sleeps two milliseconds in a loop and records how much later than that the loop actually ran it. A coroutine that logs 200 records inline is not interrupted; the ticker simply does not run until the burst finishes, and the delay shows up as one enormous sample.
| Sink | Mode | 200 records took | Worst loop delay | Late samples |
|---|---|---|---|---|
| slow (5 ms per record) | inline | 1,021 ms | 1,021 ms | 1 of 508 |
| slow (5 ms per record) | through a queue | 1.9 ms | 1.98 ms | 0 of 500 |
| fsync per record | inline | 1,089 ms | 1,087 ms | 1 of 540 |
| fsync per record | through a queue | 1.8 ms | 1.93 ms | 0 of 499 |
The median of the ticker’s samples stays at 0.10 ms in every row, and that is the misleading part: the loop was healthy for every sample except one, and that one sample is a second of stopped time – long enough for every timeout, health check and websocket keepalive in the process to expire. The worst delay is the number to watch, not the p95: 1,021 ms inline against 1.98 ms through the queue.
The queue is not free, and its price is measurable: 1.8 ms to hand over 200 records is about 9.0 microseconds each – the cost of a lock, a queue slot and a thread wakeup – where the fsync it defers costs 5.69 milliseconds. The trade is two orders of magnitude, and it is the same trade section 7 shows the other side of: a bounded queue that fills starts dropping, and a process that exits without draining loses what it holds.
7. A full queue drops loudly, a hasty exit drops silently
Moving the write off the request thread introduces the second failure: the queue is a buffer with a size, and a sink that falls behind fills it. QueueHandler handles that by not waiting – it calls put_nowait on the queue it was given – so a full queue raises queue.Full inside the handler, and logging’s handleError prints a full traceback and forgets the record. The probe fills a queue of 100 with 500 records while the listener takes five milliseconds per record, and captures stderr to see what the caller was told. The queue is full before the burst is a fifth of the way through, so what the burst measures is one full queue and three hundred-odd refusals, not a queue that is gradually filling.
from __future__ import annotations
import contextlib
import io
import logging
import logging.handlers
import pathlib
import queue
import time
import common
QUEUED_CHILD = '''
import logging, logging.handlers, queue, sys, time
path, total = sys.argv[1], int(sys.argv[2])
handler = logging.FileHandler(path)
handler.setFormatter(logging.Formatter("%(message)s"))
channel = queue.Queue(maxsize=1000)
logging.getLogger("app").addHandler(logging.handlers.QueueHandler(channel))
logging.getLogger("app").setLevel(logging.INFO)
listener = logging.handlers.QueueListener(channel, handler)
listener.start()
write = logging.getLogger("app").info
for index in range(total):
write("record %d %s", index, "q" * 104)
# no listener.stop(): the process exits with whatever the thread still holds
'''
CAPACITY = 100
TOTAL = 500
SINK_S = 0.005
class Slow(logging.Handler):
"""A sink that takes five milliseconds per record, and counts what it wrote."""
def __init__(self) -> None:
super().__init__()
self.delivered: list[str] = []
def emit(self, record: logging.LogRecord) -> None:
self.format(record)
time.sleep(SINK_S)
self.delivered.append(record.getMessage())
def stop_draining(channel: queue.Queue, listener: logging.handlers.QueueListener,
deadline: float = 30.0) -> None:
"""Stop the way a shutdown has to: wait for room, then wait for the thread.
``QueueListener.stop`` puts the sentinel with ``put_nowait``, which a full
queue refuses. A blocking put waits until the listener has taken one record,
so the sentinel goes in behind every record still queued and the thread
writes them all before it stops.
"""
channel.put(listener._sentinel, timeout=deadline)
listener._thread.join(deadline)
def full_queue(directory: pathlib.Path, stop: str) -> dict:
"""Log 500 records into a queue of 100 with a listener that takes 5 ms each."""
logger = logging.getLogger(f"probe-05-full-{stop}")
logger.setLevel(logging.INFO)
logger.propagate = False
logger.handlers.clear()
channel: queue.Queue = queue.Queue(maxsize=CAPACITY)
sink = Slow()
logger.addHandler(logging.handlers.QueueHandler(channel))
listener = logging.handlers.QueueListener(channel, sink)
listener.start()
noise = io.StringIO()
start = time.perf_counter()
with contextlib.redirect_stderr(noise):
for index in range(TOTAL):
logger.info("record %d %s", index, common.PAYLOAD)
elapsed_ms = (time.perf_counter() - start) * 1000
stop_raised = ""
strand = 0
if stop == "standard":
try:
listener.stop()
except queue.Full as exc:
# The stock stop() puts its sentinel with put_nowait, so a full queue
# refuses it and the listener keeps running. Whatever is in the queue
# at that moment is discarded here, which is what the shutdown does.
stop_raised = type(exc).__name__
while True:
try:
channel.get_nowait()
strand += 1
except queue.Empty:
break
listener.stop()
else:
stop_draining(channel, listener)
logger.handlers.clear()
printed = noise.getvalue()
delivered = len(sink.delivered)
refused = printed.count("--- Logging error ---")
if delivered + refused + strand != TOTAL:
raise SystemExit(f"{TOTAL} records but {delivered} + {refused} + {strand}")
return {"stop": stop, "records": TOTAL, "capacity": CAPACITY, "sink_ms": SINK_S * 1000,
"elapsed_ms": round(elapsed_ms, 1), "delivered": delivered,
"refused_at_put": refused, "discarded_by_shutdown": strand,
"printed_logging_errors": refused,
"printed_queue_full": printed.count("queue.Full"),
"printed_bytes": len(printed),
"listener_stop_raised": stop_raised}
| Situation | Records | Delivered | Refused at the put | In the queue when it ended | Printed errors | stderr written |
|---|---|---|---|---|---|---|
queue of 100, slow listener, the stock stop() | 500 | 2 | 398 | 100 | 398 | 414,318 bytes |
the same burst, a stop() that waits for room | 500 | 103 | 397 | 0 | 397 | 414,468 bytes |
| the same burst, counting handler (section 8) | 500 | 100 | 400 | 0 | 0 | 0 bytes |
queue of 1,000, process exits without stop() | 500 | 1 | 0 | 499 | 0 | 0 bytes |
The first row is the one to read twice, because the number a reader would call “dropped” is three numbers. 2 records reached the sink, 398 were refused by put_nowait with a traceback each – 414,318 bytes of stderr on the thread the queue was meant to unblock, for 79.1 milliseconds of work – and 100 were in the queue when the burst ended. Those hundred are not dropped by the queue at all. They are dropped by the shutdown: QueueListener.stop() puts its sentinel with put_nowait too, so a full queue refuses it, and the code that wants to stop has to empty the queue by hand before it can stop – throwing away every record it takes out.
The second row is the same burst stopped by a shutdown that waits for room instead. stop_draining is the whole difference: the sentinel goes in with a blocking put instead of put_nowait, so it waits until the listener has taken one record and then lands behind everything still queued, and the thread writes all of it before it stops: 103 of 500 delivered, nothing discarded, and 397 refusals at the other end of the pipe. That join needs a deadline as much as the put does: a blocking put on a sink that will never drain is a shutdown that never finishes.
The third row is the same burst with a handler that counts instead of printing. 100 records went in, 100 came out, and the 400 that did not fit became a number – 0 bytes on stderr. Nothing is fixed by the counter; the loss is made visible, which is the difference between a graph that is flat and a graph that is wrong.
The fourth row is the consequence when nobody tries at all – a child that logs through a queue and leaves without stopping it:
from __future__ import annotations
import pathlib
import subprocess
import sys
import common
def exits_without_stopping(directory: pathlib.Path, trial: int) -> dict:
"""A child that logs through a queue and leaves without draining it."""
path = directory / f"nostop-{trial}.log"
path.unlink(missing_ok=True)
child = subprocess.run(
[sys.executable, "-c", QUEUED_CHILD, str(path), "500"],
capture_output=True, text=True, timeout=120)
lines = common.read_lines(path)
return {"records": 500, "on_disk": len(lines), "lost": 500 - len(lines),
"exit_code": child.returncode, "stderr": child.stderr.strip()[:200]}
A process that logs 500 records through a queue and exits without calling stop() leaves 1 of them on disk – never more than 1 in 5 runs – and reports success, exit code 0. There is no traceback to search for and no error in the exit code, because nothing failed – the records simply never reached a file.
Why the queue must have a size: An unbounded queue is not the answer either. It removes the drop and moves the problem to memory: a sink that is slower than the service does not stop the service, it grows the queue until the container’s limit ends the process, and everything still in the queue goes with it. The measured record for that trade is the no-stop row: whatever the queue holds at exit is lost, and an unbounded queue holds more.
8. logguard: the lock, the follow, the count
The two guards are small enough to read in one sitting, and neither asks for a new call site. The rotating handler is a subclass of the standard one with the same constructor arguments plus the lock file’s suffix, so the class name is the only change at the call site; the queue handler takes the queue and a counter that the standard pair did not have. The rotating handler serialises rollover with a flock on a sidecar file and re-checks the decision under that lock, then follows the file when another process has moved it. The queue handler counts what it cannot enqueue – and what its sink could not write – instead of printing it, and the listener stops by waiting for room up to a deadline rather than raising or waiting forever on a sink that never drains.
"""A rotating file handler that keeps its promise when several processes write.
``logging.handlers.RotatingFileHandler`` assumes one writer: each ``emit``
checks its own stream's position, and a rollover renames the file under the
other writers' feet. Two processes then rename and delete each other's files,
the winner's rename raises ``FileNotFoundError`` (and logging drops that
record), and the file each loser still holds has been unlinked from the chain,
so everything written to it is gone.
This handler makes two changes, both small:
* rollover runs under an exclusive ``flock`` on a sidecar lock file, and the
decision to roll is retaken under that lock, so only one process moves files
at a time;
* every ``emit`` compares the inode it opened with the inode now at the path,
and reopens when they differ, so a process whose file was rotated away
continues in the file the chain is actually keeping.
The rollover decision itself is the standard one, and it is worth saying so: the
file rolls when the record that is about to be written would take it past
``maxBytes``, not when it is already past. Comparing only the current size and
rolling afterwards is the bug this class does not have - it leaves the file one
record over the limit, and every record in that last stretch takes the lock to
find out there is nothing to do. So ``shouldRollover`` measures the file this
handler holds (not its stale stream position) and adds the formatted record;
``emit`` asks that question first, and asks it again under the lock, where
another process may already have made room by rolling.
What a caller does with ``doRollover`` is a separate contract. A SIGHUP handler,
a timer or a logrotate hook calls it to rotate *now*, whatever the file's size,
and the standard class rotates in that case; this one does too, under the lock.
Asking the size question there as well would make the same call refuse to rotate
a half-full file, which is neither what the standard class does nor what a caller
asking for a rotation means. What it does not do is rotate a file another process
has already rotated: it takes the lock, compares the file it holds with the one
at the path, and when they differ it reopens the new file and returns without
moving anything. One signal sent to a pool of workers is one rotation - without
that check every worker that received the signal would shift the whole backup
chain down by one, and the newest lines would be deleted before anyone read
them. ``emit`` never relies on either path: it decides for itself, before it
writes the record that would not fit.
Two smaller decisions keep a log call from failing at the worst moment. A
sidecar lock that cannot be opened (a read-only directory, a full descriptor
table, a lock path someone made a directory) is counted in ``follow_errors``
and the record is written to the file this handler already holds, because a
line in the wrong file beats an exception in the request path. And the lock
file is left on disk on purpose: deleting it would let the next process create
a new inode and serialise against nobody. A rollover that fails is the other
case and gets the other answer: a rename that cannot happen - the backup name
taken by a directory, a full mount, a directory that went read-only - means the
record about to be written has no file to go to, so it is counted in
``rollover_errors`` and handed to ``handleError``, which is what the standard
handler does with an emit it could not finish. The counters are kept apart
because the operator's next move differs: a lock that could not be opened still
left a record in the file this handler holds, and a roll that failed lost one.
"""
from __future__ import annotations
import contextlib
import fcntl
import logging
import logging.handlers
import os
import pathlib
import typing
class RotatingFileHandler(logging.handlers.RotatingFileHandler):
"""Rotate once, under a lock, and follow the file when someone else moves it.
The constructor takes the arguments of the standard handler plus
``lock_suffix``, the name appended to the log path for the lock file.
"""
def __init__(self, filename: str | os.PathLike[str], mode: str = "a", maxBytes: int = 0,
backupCount: int = 0, encoding: str | None = None, delay: bool = False,
errors: str | None = None, lock_suffix: str = ".lock") -> None:
if maxBytes < 0:
raise ValueError("maxBytes must be zero or more")
if backupCount < 0:
raise ValueError("backupCount must be zero or more")
self.lock_path = pathlib.Path(f"{filename}{lock_suffix}")
self.rotations = 0
self.reopens = 0
self.follow_errors = 0
self.rollover_errors = 0
self.skipped_rollovers = 0
self._inode: int | None = None
self._pending_bytes = 0 # the record emit is deciding about, formatted
super().__init__(filename, mode, maxBytes, backupCount, encoding, delay, errors)
def _open(self) -> typing.IO:
"""Open the file and remember which inode this handler now owns."""
stream = super()._open()
self._inode = os.fstat(stream.fileno()).st_ino
return stream
@contextlib.contextmanager
def _locked(self) -> typing.Iterator[None]:
"""Hold an exclusive lock shared by every process using this log path."""
self.lock_path.parent.mkdir(parents=True, exist_ok=True)
fd = os.open(self.lock_path, os.O_CREAT | os.O_RDWR, 0o644)
try:
fcntl.flock(fd, fcntl.LOCK_EX)
yield
finally:
fcntl.flock(fd, fcntl.LOCK_UN)
os.close(fd)
def _moved(self) -> bool:
"""True when the path no longer names the file this handler opened.
Two tests, because a file can be taken away two ways: renamed (its name
is now the backup) and deleted. ``st_nlink`` is the one that catches a
deletion even when the kernel hands the freed inode number to the new
file; comparing the inode catches the rename, in which the old file is
still alive under its new name.
"""
if self.stream is None or self.stream.closed or self._inode is None:
return False
if os.fstat(self.stream.fileno()).st_nlink == 0:
return True
try:
return os.stat(self.baseFilename).st_ino != self._inode
except FileNotFoundError:
return True
def _reopen(self) -> None:
"""Close this handler's stream and open the file now at the path."""
if self.stream is not None:
self.stream.close()
self.stream = None
self.stream = self._open()
self.reopens += 1
def _size(self) -> int:
"""The size of the file this handler writes, read from its own stream."""
if self.stream is None or self.stream.closed:
return 0
return os.fstat(self.stream.fileno()).st_size
def emit(self, record: logging.LogRecord) -> None:
"""Follow, roll if this record would not fit, then write it.
The two failure paths are kept apart on purpose. A lock or a reopen that
cannot happen leaves a record that still has a file: it goes to the one
this handler holds and is counted in ``follow_errors``. A roll that
fails leaves no file for the record at all, so the record is reported
through ``handleError`` and counted in ``rollover_errors`` instead of
being dropped in silence.
"""
if self.maxBytes > 0:
try:
if self._moved():
with self._locked():
if self._moved(): # re-checked: another writer may have won
self._reopen()
roll = self.shouldRollover(record)
except OSError:
# No lock and no reopen: keep the record in the file this handler
# holds rather than raise into the thread that was logging.
self.follow_errors += 1
roll = False
if roll:
try:
with self._locked():
if self._should_rollover_locked():
self._rotate()
except OSError:
self.rollover_errors += 1
self.handleError(record)
return
logging.FileHandler.emit(self, record)
def shouldRollover(self, record: logging.LogRecord) -> bool: # noqa: N802 - logging API
"""Would this record take the file past ``maxBytes``?
The standard rule, with the size read from the descriptor this handler
holds instead of from its stream position, which is the other writers'
business as much as this one's. Three cases keep it honest: nothing rolls
while ``maxBytes`` is zero; nothing rolls an empty file (a handler that
does spins a whole backup chain away on a record bigger than the limit);
and nothing rolls a path that is not a regular file.
"""
if self.maxBytes <= 0:
return False
if self.stream is None: # delay was set
self.stream = self._open()
size = self._size()
if size == 0: # never roll an empty file
return False
message = self.format(record)
self._pending_bytes = len(message) + len(self.terminator)
if size + self._pending_bytes < self.maxBytes:
return False
return os.path.isfile(self.baseFilename) # never roll anything else
def _should_rollover_locked(self) -> bool:
"""The same question again, now that this process holds the lock.
Another writer may have rolled while this one waited for the lock, and
there are two ways to notice: the path no longer names the file this
handler holds (follow the new one and write this record there), or the
file is still this one but another writer's roll made room in it (skip).
Only when neither is true does the record ``emit`` is holding justify
moving the files.
"""
if self._moved():
self._reopen()
return False
if self._size() == 0: # never roll an empty file
return False
if self._size() + self._pending_bytes < self.maxBytes:
return False # another writer's roll made room
return os.path.isfile(self.baseFilename)
def _rotate(self) -> None:
"""Move the files; the caller holds the lock."""
super().doRollover()
self.rotations += 1
def doRollover(self) -> None: # noqa: N802 - logging API
"""Rotate now, under the lock - what calling this directly means.
The standard handler rotates on this call whatever the file's size, so a
SIGHUP handler or a timer that calls it gets a rotation rather than a
question. The size rule lives in ``shouldRollover``, which ``emit`` asks
before it takes the lock; nothing here re-asks it.
What it does ask, once the lock is held, is whether the work is already
done: a signal sent to every worker reaches this call in each of them,
and the first one to take the lock rotates the file the others are still
holding. When the path no longer names this handler's file, the handler
reopens the one that is now at the path and returns without moving
anything, so a broadcast is one rotation and not one per worker.
"""
with self._locked():
if self._moved():
self._reopen()
self.skipped_rollovers += 1
return
self._rotate()
def health(self) -> dict:
"""What a dashboard needs: which file this handler owns, and what it did."""
return {
"path": self.baseFilename,
"inode": self._inode,
"size_bytes": self._size(),
"max_bytes": self.maxBytes,
"backups": self.backupCount,
"rotations": self.rotations,
"reopens": self.reopens,
"skipped_rollovers": self.skipped_rollovers,
"follow_errors": self.follow_errors,
"rollover_errors": self.rollover_errors,
"moved_by_another_writer": self._moved() if self._inode is not None else False,
}
Six details in that file decide whether the guard works. shouldRollover asks the standard question – would the record about to be written take the file past maxBytes – but measures the file this handler holds rather than its stale stream position. emit takes the lock only when that answer is yes, and asks the question again inside the lock, because another process may have rolled while this one waited: if the path no longer names the handler’s file it follows the new one, and if the file has room it writes and moves nothing. _moved() tests identity two ways – the inode the handler opened against the one at the path, and the link count of its own descriptor – because a file can be taken away by a rename, which leaves it alive under a new name, or by a delete, which leaves the handler writing to a file with no name at all. And emit reopens before writing rather than after, so the record that would have gone to the moved file goes to the one the chain is keeping. A fifth is the one that keeps a log call from failing at the worst moment: when the sidecar lock cannot be opened – a read-only directory, a full descriptor table, a lock path someone made a directory – the handler counts it in follow_errors and writes to the file it already holds instead of raising into the request path. A line in the wrong file beats an exception at the moment a service is trying to tell you something. The sixth is the other half of that decision: when the lock was there and the roll itself failed – the backup name taken, the mount full, the directory gone read-only – there is no file for the record to go to, so it is counted in rollover_errors and reported through handleError, which is what the standard handler does with an emit it could not finish. Two counters, because the news differs: one says a line landed in the file this process still holds, the other says a line is gone.
Two behaviours of doRollover() are worth separating, and it is the call a SIGHUP handler or a timer uses. The first is the standard contract: it rotates the file the handler holds, whatever its size, exactly as the standard class rotates on that call – asking the size question there as well would make the same call refuse a half-full file, and the guard the article measured would be one that cannot be told to roll. The second is that it does not do the work twice. A signal sent to a pool reaches doRollover in every worker, and the first one to take the lock has already moved the file the others are holding; when the path no longer names this handler’s file, the handler reopens the new one and returns. Without that check a broadcast shifts the whole backup chain down by one generation per worker and deletes the newest lines before anyone reads them; with it, one signal is one rotation, and skipped_rollovers says how many workers only followed.
"""A bounded queue sink that says how many records it dropped, and stops cleanly.
``QueueHandler`` plus ``QueueListener`` is the standard way to take logging off
a request thread, and the standard pair has two sharp edges measured in this
article's probes:
* when the queue is full, ``QueueHandler`` calls ``put_nowait`` and the record
is dropped through ``handleError``, which prints a traceback per dropped
record - hundreds of kilobytes of noise, on the thread the queue was meant to
free, and no counter anywhere;
* ``QueueListener.stop`` enqueues its sentinel with ``put_nowait`` too, so on a
full queue it raises ``queue.Full`` and leaves the thread running; the
records it still held are lost at exit, silently.
``CountingQueueHandler`` puts the record in without formatting it and counts
what did not fit; ``Listener`` stops by putting the sentinel with a blocking
put that waits for room up to a deadline, instead of raising on a full queue or
waiting on a sink that will never drain; ``CountingSink`` counts a record as
delivered only when the wrapped handler actually wrote it, and counts a write
that failed - whether it raised or was swallowed by the handler's own
``handleError`` - as ``failed`` rather than letting the listener thread die.
Together they make the loss visible instead of silent.
"""
from __future__ import annotations
import logging
import logging.handlers
import queue
import threading
import time
class DropCounter:
"""Thread-safe counters for one queue: what went in, what came out, what did not.
``dropped`` counts the records that never got into the queue; ``failed`` counts
the ones that got in and whose sink then raised. They are kept apart because
they call for different fixes - a bigger queue against a sink that cannot write -
and because a delivered record has to mean a written record, not a dequeued one.
"""
def __init__(self) -> None:
self._lock = threading.Lock()
self._enqueued = 0
self._delivered = 0
self._dropped = 0
self._failed = 0
def add(self, field: str, amount: int = 1) -> None:
if field not in ("enqueued", "delivered", "dropped", "failed"):
raise ValueError(f"unknown counter {field!r}")
if amount < 0:
raise ValueError("a counter only moves forward")
with self._lock:
setattr(self, f"_{field}", getattr(self, f"_{field}") + amount)
def snapshot(self) -> dict:
"""The four counters, plus the share of records that never reached the sink."""
with self._lock:
enqueued, delivered = self._enqueued, self._delivered
dropped, failed = self._dropped, self._failed
offered = enqueued + dropped
return {
"enqueued": enqueued,
"delivered": delivered,
"dropped": dropped,
"failed": failed,
"offered": offered,
"drop_ratio": round(dropped / offered, 4) if offered else 0.0,
}
class CountingQueueHandler(logging.Handler):
"""Hand a record to a queue without waiting, and count the ones that do not fit.
The queue must be bounded (``maxsize`` greater than zero) for a drop to
happen at all; an unbounded queue trades the drop for a memory leak, which
the article measures separately as a queue that grows with the backlog.
"""
def __init__(self, channel: queue.Queue, counter: DropCounter,
level: int = logging.NOTSET) -> None:
super().__init__(level)
if not callable(getattr(channel, "put_nowait", None)):
raise TypeError("channel must offer put_nowait(record), as queue.Queue does")
self.channel = channel
self.counter = counter
def emit(self, record: logging.LogRecord) -> None:
try:
self.channel.put_nowait(record)
except queue.Full:
self.counter.add("dropped")
return
self.counter.add("enqueued")
def handleError(self, record: logging.LogRecord) -> None: # noqa: N802 - logging API
"""Never print: a dropped record is a counter, not a stderr flood."""
self.counter.add("dropped")
class _WriteFailure:
"""Stands in for a handler's ``handleError`` while one record is written."""
def __init__(self) -> None:
self.happened = False
def handle(self, record: logging.LogRecord) -> None:
"""Record that the write failed and print nothing, as the sink promises."""
self.happened = True
class CountingSink(logging.Handler):
"""Wrap the real handler so the listener can count what it actually wrote.
Three ways a record reaches this class and still must not be counted as
delivered: a filter on the wrapped handler rejects it (``handle`` returns
``False``); the wrapped handler raises; or the wrapped handler's own
``emit`` swallows a write error and calls ``handleError``. The second one
used to take the listener thread down with it - the exception escaped
``QueueListener``'s monitor loop, so one unwritable record ended every record
after it. The third is the one a ``StreamHandler`` produces, and it is
silent: ``StreamHandler.emit`` catches ``OSError`` (a closed pipe, a full
disk) and hands it to ``handleError``, which by default prints a traceback,
so ``handle`` returns ``True`` and a naive wrapper counts the record as
delivered while nothing was written.
Both are counted in ``failed`` and the thread goes on: a sink that fails on
one line should not stop logging. ``handleError`` is swapped on the wrapped
handler for the length of one write and swapped back, because the listener
thread is the only caller of this sink.
"""
def __init__(self, inner: logging.Handler, counter: DropCounter,
level: int = logging.NOTSET) -> None:
super().__init__(level)
self.inner = inner
self.counter = counter
def emit(self, record: logging.LogRecord) -> None:
failure = _WriteFailure()
own = vars(self.inner).get("handleError")
self.inner.handleError = failure.handle # type: ignore[method-assign]
try:
accepted = self.inner.handle(record)
except Exception: # noqa: BLE001 - a failed write is a counter, not a dead thread
self.counter.add("failed")
return
finally:
if own is None:
del self.inner.handleError
else:
self.inner.handleError = own
if failure.happened:
self.counter.add("failed")
return
if accepted is not False:
self.counter.add("delivered")
def close(self) -> None:
self.inner.close()
super().close()
class Listener(logging.handlers.QueueListener):
"""A listener that stops inside a deadline instead of raising or hanging."""
def stop(self, timeout: float = 10.0) -> None: # noqa: D401 - logging API
"""Wait for room, then for the thread - and give up after ``timeout`` seconds.
A blocking put with no deadline is a hang when the sink is stuck (a full
pipe, a server that stopped reading): the sentinel never gets in and the
shutdown path waits forever. Both waits share one budget, and running out
of it raises ``TimeoutError`` with the listener's state still readable.
"""
thread = self._thread
if thread is None or not thread.is_alive():
self._thread = None
return
deadline = time.monotonic() + timeout
try:
self.queue.put(self._sentinel, timeout=timeout)
except queue.Full:
raise TimeoutError(
f"the queue stayed full for {timeout} s; the listener is still running") from None
thread.join(max(0.0, deadline - time.monotonic()))
if thread.is_alive():
raise TimeoutError(f"listener did not stop within {timeout} s")
self._thread = None
CountingQueueHandler.emit stores the LogRecord itself rather than a formatted string, which keeps formatting on the listener thread – and is correct only because the listener is a thread in the same process. A queue that crosses a process boundary needs record.getMessage() or self.format(record) before it is put, because the record holds references to the caller’s objects. CountingSink counts a record as delivered only when the wrapped handler actually wrote it, and counts a write that failed as failed instead of letting the exception end the listener thread – which is what a plain QueueListener does with an unwritable record: the monitor loop dies and every record after it is lost with the queue.
A write failure has two shapes, and only one of them raises. A sink whose own emit raises is caught. A StreamHandler – the standard library’s file and stream handlers – catches the OSError itself and calls handleError, so handle() returns True and nothing reaches the sink: a closed pipe or a full disk would be counted as delivered. CountingSink therefore swaps in its own handleError for the length of the write and swaps the handler’s method back afterwards; both shapes land in failed, and neither prints a traceback.
The price of the identity check is the one number that surprised this run, and the first thing to get right about it is when it is paid. It is measured by timers around each handler – the second half of the probe whose four-writer half section 4 prints – so the numbers below describe a cost rather than a block a reader can run. With maxBytes at zero the guard never calls the check: emit tests the limit first, so on the tmpfs mount the two handlers are the same call – 7.6 microseconds against 7.6 – and what separates them is the spread between runs, not a cost. Turn rotation on and the check runs once per record: 12.5 microseconds against 9.3 for the standard handler on local storage, where the check itself is 2.5 microseconds.
On the network mount the same check is not microseconds but a round trip, and the controls say which part of it is which. One call of the handler’s own check, straight after a record is written, costs 4.400 ms; the same two system calls timed by hand cost 4.520 ms, so the handler’s check and the hand-written pair agree within the spread between runs. Each half measured on its own pays the whole round trip – 4.513 ms for the fstat of the handler’s own descriptor, 4.494 ms for the stat of the path – and that is the clue: the pair is one round trip, not two, because the second call, whose attributes the first has just fetched, costs 2.1 microseconds, and with nothing written in between the pair costs only 2.4 microseconds – against 2.5 microseconds for the same check on the local mount.
Waiting does not make that difference: 4.863 ms after 20 milliseconds, and 6.522 ms after 5 seconds – 8 of 8 checks that waited took the full round trip. If the answer were merely late it would be local by then; it is not, and no wait brings a local answer back. An fsync before the check does make it cheap, at 0.072 ms, but an fsync flushes the data and returns after the host has handled the file, and one call cannot say which of those two did the work. The write that is already synchronous can: the same record written with os.O_SYNC takes 4.617 ms to write – the round trip moved into the write, where a buffered write never goes – and the check behind it costs 0.048 ms. So there is one round trip per written record on this mount, and it is paid by the write when the write is synchronous and by the first call that asks for the file’s attributes when it is not. The check is not expensive; asking a network filesystem about a file the guest has just changed is, once per record, for as long as the file keeps being written.
| Measurement | Mount | Median per record | What it shows |
|---|---|---|---|
| standard handler, no rotation | tmpfs | 7.6 us | the baseline write |
| locked handler, no rotation | tmpfs | 7.6 us | the guard, with the check not called at all |
| standard handler, rotating | tmpfs | 9.3 us | the same 2,000 records, rolled by the standard class |
| locked handler, rotating | tmpfs | 12.5 us | the check, the lock and the rolls |
| the identity check, nothing written between | virtiofs | 2.4 us | two calls, attributes valid |
| the identity check straight after a write | virtiofs | 4.400 ms | the guard’s own check, one round trip |
| the same two calls timed by hand | virtiofs | 4.520 ms | the control for the row above |
| the same check 20 ms after the write | virtiofs | 4.863 ms | a short wait does not refresh them |
| the same check 5 s after the write | virtiofs | 6.522 ms | 8 of 8 still took the round trip |
| the same check after an fsync | virtiofs | 0.072 ms | the flush returned them, and one call cannot say which half did it |
the same check after an os.O_SYNC write | virtiofs | 0.048 ms | the write paid it instead, 4.617 ms |
If your log path is a network mount: On a network filesystem the per-record identity check is a round trip, and no amount of cleverness in the check avoids it. Two options are honest: keep the log on local storage or a mount with attribute caching, which is where logs belong; or set the handler’s maxBytes to zero and let an external rotator own the files, accepting that the handler then cannot follow a move. Section 9 takes the first option and says why.
The suite is 40 tests in 3 files, 475 lines of package and 799 lines of test, and it runs in 1.34 seconds. The shared fixture starts a real second process and kills anything a test leaves behind, because the defect this article is about does not exist inside one process.
"""Shared fixtures for the logguard tests: a real second process, and cleanup.
The rotation test needs more than one writer, and a thread is not a second
writer for this purpose: the defect is that two processes each hold their own
descriptor. So the worker below runs as a subprocess with this package on its
path, and the fixture kills anything it started before the test returns.
"""
from __future__ import annotations
import os
import pathlib
import subprocess
import sys
import time
import pytest
PACKAGE_ROOT = pathlib.Path(__file__).resolve().parents[2]
WORKER = '''
import logging, sys, time
sys.path.insert(0, sys.argv[1])
from logguard import RotatingFileHandler
path, worker, total, max_bytes, backups, start = (sys.argv[2], int(sys.argv[3]),
int(sys.argv[4]), int(sys.argv[5]), int(sys.argv[6]), float(sys.argv[7]))
handler = RotatingFileHandler(path, maxBytes=max_bytes, backupCount=backups)
handler.setFormatter(logging.Formatter("%(message)s"))
logger = logging.getLogger("worker-%d" % worker)
logger.setLevel(logging.INFO)
logger.propagate = False
logger.addHandler(handler)
while time.time() < start:
pass
for index in range(total):
logger.info("worker %d record %d %s", worker, index, "z" * 104)
handler.close()
'''
@pytest.fixture()
def log_dir(tmp_path: pathlib.Path) -> pathlib.Path:
"""An empty directory for one test's log files."""
directory = tmp_path / "logs"
directory.mkdir()
return directory
def start_workers(path: pathlib.Path, workers: int, records: int, max_bytes: int,
backups: int) -> list[subprocess.Popen]:
"""Start ``workers`` subprocesses that all log to ``path`` at the same instant."""
start = time.time() + 0.4
return [subprocess.Popen(
[sys.executable, "-c", WORKER, str(PACKAGE_ROOT), str(path), str(worker),
str(records), str(max_bytes), str(backups), str(start)],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
for worker in range(workers)]
def finish_workers(children: list[subprocess.Popen]) -> list[str]:
"""Wait for every worker, killing any that outlive their budget."""
errors: list[str] = []
for child in children:
try:
_, stderr = child.communicate(timeout=60)
except subprocess.TimeoutExpired:
child.kill()
_, stderr = child.communicate(timeout=30)
errors.append("worker killed after 60 s")
if child.returncode != 0:
errors.append(f"worker exit {child.returncode}: {stderr.strip()[:200]}")
elif stderr.strip():
errors.append(f"worker wrote to stderr: {stderr.strip()[:200]}")
return errors
def read_all(directory: pathlib.Path) -> list[str]:
"""Every line of every file in ``directory`` whose name starts with app.log."""
lines: list[str] = []
for path in sorted(directory.glob("app.log*")):
if path.name.endswith(".lock"):
continue
lines.extend(path.read_text(errors="replace").splitlines())
return lines
@pytest.fixture(autouse=True)
def no_stray_children() -> object:
"""Fail loudly if a test leaves a subprocess behind."""
before = {child.pid for child in _children()}
yield
after = {child.pid for child in _children()}
new = after - before
for pid in new:
try:
os.kill(pid, 9)
except OSError:
continue
assert not new, f"test left {len(new)} child process(es) running"
def _children() -> list[pathlib.Path]:
return [path for path in pathlib.Path("/proc").iterdir()
if path.name.isdigit() and _parent_of(path) == os.getpid()]
def _parent_of(pid_path: pathlib.Path) -> int:
try:
for line in (pid_path / "status").read_text().splitlines():
if line.startswith("PPid:"):
return int(line.split()[1])
except (FileNotFoundError, ProcessLookupError, PermissionError):
return -1
return -1
The test that matters is the one that reproduces the article’s headline without any of the probe’s machinery: four subprocesses, one path, and an assertion about each writer’s newest records.
from __future__ import annotations
import logging
import pathlib
from conftest import finish_workers, read_all, start_workers
def write(logger: logging.Logger, count: int, tag: str = "line") -> None:
for index in range(count):
logger.info("%s %d %s", tag, index, LINE)
def test_four_writers_keep_every_writers_newest_records(log_dir: pathlib.Path) -> None:
"""The defect the handler exists for: four processes, one file, rotated."""
path = log_dir / "app.log"
children = start_workers(path, workers=4, records=200, max_bytes=32768, backups=3)
errors = finish_workers(children)
assert errors == []
lines = read_all(log_dir)
present: dict[int, set[int]] = {}
for line in lines:
parts = line.split()
if len(parts) >= 4 and parts[0] == "worker" and parts[2] == "record":
present.setdefault(int(parts[1]), set()).add(int(parts[3]))
assert set(present) == {0, 1, 2, 3}, "every writer must be represented"
for worker, indices in present.items():
missing = [index for index in range(180, 200) if index not in indices]
assert not missing, f"writer {worker} lost its newest records {missing}"
The queue has the same shape of test: fill the queue before the listener exists, so the counts are the queue’s size and the burst’s size rather than a race between two threads, then check that nothing was printed. The second assertion is the one that fails on the standard pair, because handleError writes the traceback to stderr.
from __future__ import annotations
import logging
import pathlib
import queue
import time
import pytest
from logguard import CountingQueueHandler, CountingSink, DropCounter, Listener
LINE = "q" * 100
def build(channel: queue.Queue, sink: logging.Handler, counter: DropCounter,
name: str) -> tuple[logging.Logger, Listener]:
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
logger.propagate = False
logger.handlers.clear()
logger.addHandler(CountingQueueHandler(channel, counter))
listener = Listener(channel, CountingSink(sink, counter))
listener.start()
return logger, listener
class Slow(logging.Handler):
"""A sink that is always behind, so the queue fills."""
def __init__(self, delay: float = 0.005) -> None:
super().__init__()
self.delay = delay
self.seen: list[str] = []
def emit(self, record: logging.LogRecord) -> None:
time.sleep(self.delay)
self.seen.append(record.getMessage())
def test_a_full_queue_is_counted_and_never_printed(capsys: pytest.CaptureFixture[str],
tmp_path: pathlib.Path) -> None:
"""The numbers are the queue's size and the burst's size, not a race between them.
The listener is created after the burst, so nothing can have left the queue
while it is being filled: exactly twenty records fit and exactly a hundred
and eighty are refused, whatever the interpreter's thread scheduler does.
"""
channel: queue.Queue = queue.Queue(maxsize=20)
counter = DropCounter()
logger = logging.getLogger("tq-full")
logger.setLevel(logging.INFO)
logger.propagate = False
logger.handlers.clear()
logger.addHandler(CountingQueueHandler(channel, counter))
for index in range(200):
logger.info("record %d %s", index, LINE)
assert channel.full(), "the burst must fill the queue before the listener starts"
assert counter.snapshot() == {"enqueued": 20, "delivered": 0, "dropped": 180,
"failed": 0, "offered": 200, "drop_ratio": 0.9}
listener = Listener(channel, CountingSink(Slow(delay=0), counter))
listener.start()
listener.stop()
snapshot = counter.snapshot()
captured = capsys.readouterr()
assert snapshot["delivered"] == 20, "every record that got in must reach the sink"
assert snapshot["offered"] == 200
assert snapshot["failed"] == 0
assert "Logging error" not in captured.err
assert "queue.Full" not in captured.err
What the suite does not cover is as deliberate as what it does: 20 tests for the handler, 15 for the queue and 5 for the exports and the small contracts, with no test for anything this article did not print, apart from two that pin down the standard library behaviour the FAQ describes. Five more keep the claims above honest: one asserts that no file ever goes over maxBytes, one runs the same sixty records through the standard handler and through this one and compares the files byte for byte, one calls doRollover() on a half-full file and checks that it rolled, one makes the rename fail and checks that the record is reported through handleError and counted in rollover_errors instead of follow_errors, and one tells two handlers on one path to roll and checks that the second only reopened.
9. The production runbook
The order matters, because each step removes a large cause before the next measurement is taken. Doing them in the reverse order – adding fsync first – makes a service slower and no more correct.
- Count the writers. One handler per process means one file per process. Gunicorn with four workers, Celery with concurrency above one, or a replica count above one on a shared volume all write to the same path. If there is more than one writer, a rotating handler is the wrong tool until it locks.
- Decide what a lost line costs. Audit records need durable writes; debug lines do not. This decision sets the fsync policy and nothing else should.
- Put the log where the attributes are local. A network mount makes every identity check a round trip – measured at 4.400 ms per record against 2.5 microseconds locally – and makes the buffer the size of the mount’s block size, which is what section 5 measured.
- Take the write off the request thread. A queue, a listener thread, and a counter for the records that did not fit. The listener must be stopped on the way out: without it, 499 of 500 records were lost with a successful exit code.
- Size the queue to the outage you accept. A queue of a hundred records absorbs a stall of a hundred records; a queue of a million absorbs the stall and the memory. The drop counter is the number that says which happened.
- Rotate under a lock, or do not rotate in-process. If the file is shared, use a handler that locks the rollover and follows a move (section 8); if it is not, the standard handler is fine and cheaper.
- Alert on the counters, not the log. Dropped records, rotations, rollovers that failed, reopens and the age of the newest line are five numbers that turn this class of incident into a graph.
- Test the crash, once. Kill the process with
SIGKILLwhile it is logging and count the lines. The number is the buffer size divided by the line size, and it is cheaper to learn that on purpose.
The whole fix, in two guards: Nothing in this runbook requires a library. The two guards in section 8 are the standard library’s own classes with one lock and one counter added, and the probe behind the four-writer comparison is printed in section 4. What is required is deciding, per service, which of the six shapes in section 2 applies – and the answer is usually in the process count, not in the log level.
10. What to put on a dashboard
Every failure in this article had one number that would have caught it before a reader noticed, and none of them is the log volume. The list below is the smallest set that covers the six shapes, and each row says where the number comes from in the two guards of section 8 or in a standard library call.
| Metric | Where it comes from | What it catches | Alert shape |
|---|---|---|---|
| records dropped | DropCounter.snapshot() | a queue that is too small for its sink, the loud loss in section 7 | any increase above zero |
| records the sink failed to write | the same snapshot’s failed count | a write that raised or that the handler swallowed: a closed pipe, a full disk, a field that will not serialise | any increase above zero |
| enqueued minus delivered and failed | the same snapshot | a listener that stopped or is falling behind | growth over minutes, not a spike |
| rotations | RotatingFileHandler.health() | a file that rolls far more often than the retention it was sized for | rate above the size and traffic allow |
| rollovers that failed | the same health record’s rollover_errors | a roll that could not rename – a lost record, reported through handleError (section 8) | any increase above zero |
| reopens | the same health record | another writer moving the file – the race of section 4, seen from inside | steady rate is expected, a burst is not |
| moved_by_another_writer | the same health record | the race itself: this process’s file is not the one at the path | true for more than a scrape |
| size against max_bytes | the health record’s two fields | rotation that is configured but never happening | ratio pinned at one with no rotations |
| age of the newest line | the log file’s modification time | logging that stopped without an error – the no-stop row of section 7 | older than the traffic allows |
| write latency p99 | the timer around logger.info() | the fsync and the network mount, sections 3 and 8 | above the event loop’s budget |
| event loop lag p99 and max | a ticker task like the one in section 6 | a handler blocking the loop, before it becomes a timeout | max above the shortest timeout in the service |
Two of those are worth more than the rest. The drop counter is the only signal that a queue is losing work, because the alternative – a traceback on stderr – is easy to miss and easy to drown: the probe printed 414,318 bytes of tracebacks to report 398 refused records. And the age of the newest line is the only signal that logging stopped, because a log that receives nothing looks exactly like a service with no traffic.
Why not volume: Log volume is the wrong metric for all of this: it goes up when things break, which looks like more information and is usually less. Each number in that table moves for a reason that is unambiguous, and each one maps to a single decision – the queue size, the retention budget, the fsync policy, and the thread the handler runs on.
11. Frequently asked questions
Is logging.handlers.RotatingFileHandler safe when several processes write the same file?
No. Each process keeps its own stream and rolls by renaming the path, so two processes rename and delete each other’s files. Measured with four writers on one path and a retention budget larger than the traffic, the standard handler kept 526 of 800 records and dropped 7 while rolling, and left 3, 4 and 4 files in its three runs, where the configuration allows four. A single writer with the same settings keeps every line it is allowed to keep.
Do I need fsync on every log record?
Only if the record must survive a machine crash, and almost no service needs that per line. One fsync per record cost 5.69 ms on the log mount measured here, which is 175.7 records a second for one thread. A flush per record – what the file handler already does – is 79.6 microseconds and survives the process, not the machine. Choose per log level: audit records durable, debug records not.
Why did my log lose its oldest lines without any error?
Because rotation deletes them. A single writer rotating at 16,384 bytes with 4 backups kept 545 of 1,200 lines with no errors at all: the retention budget is 81,920 bytes, and older lines must go for new ones to fit. The file count is the first check: if one file is missing from the chain, a competing writer took it. It is not the only one – a race can leave the configured number of files and still lose lines – so the test that settles it is the newest records of each writer, which section 4 counts.
How do I know when a QueueHandler drops records?
The standard one does not tell you. It raises inside the handler, logging prints a traceback per dropped record and forgets it, so the only evidence is stderr – 398 tracebacks and 414,318 bytes in one measured burst. A counting handler replaces that with a counter: the same burst reported 400 drops and printed 0 bytes.
Does QueueListener need to be stopped?
Yes, and it must be stopped with something that waits. A process that logged 500 records through a queue and exited without stop() left 1 of them on disk and reported success. The standard stop() also puts its sentinel with put_nowait, so on a full queue it raises queue.Full in the shutdown path; the measured exception name was Full, and the 100 records still in the queue were lost when the caller emptied it to stop at all. A stop that waits for room delivered them instead – 103 of 500 rather than 2 – and needs a deadline as well, because a blocking put on a sink that will never drain is a shutdown that never finishes. The guard in section 8 does both.
Why did SIGKILL lose everything on one host and only twenty lines on another?
Because the buffer is sized by the filesystem, and the filesystem’s block size replaces the default rather than being compared with it. io.DEFAULT_BUFFER_SIZE is 8,192 bytes, but a file opened with default buffering on the network mount first reaches the disk after 1,048,576 bytes – its st_blksize – and on tmpfs after 4,096, which is smaller than the default. The same code lost 1,000 of 1,000 records on the first and 20 on the second.
If the buffer is lost on a kill, is sys.exit() as bad?
No. sys.exit() raises SystemExit; the interpreter runs its normal shutdown and flushes every buffered stream, so the child that logged 1,000 records through an unflushed handler left 1,000 of them on disk, against 0 for os._exit() and 0 for SIGKILL. The calls that skip the flush are os._exit() and a fatal signal – which is what an OOM killer, a container runtime and kill -KILL use.
Does logging block asyncio?
Yes, for as long as the handler takes, on the loop’s own thread. Two hundred records through an fsync handler held the loop for 1,089 ms; the same 200 through a QueueHandler took 1.8 ms and the worst ticker delay was 1.93 ms. The median ticker delay was 0.10 ms in both cases, which is why a p95 dashboard misses it.
Should I use WatchedFileHandler and an external rotator instead?
It is the right answer when something outside the process already owns the files, such as logrotate or a container runtime. WatchedFileHandler stats the path on every emit and reopens when that stat fails or when the device and inode differ from the ones it opened, so it does notice a rename and a deletion both, and it recreates a file that was deleted while it held it. What it does not do is rotate: the size limit, the retention and the backup chain are the external rotator’s job. It also cannot make two of your own processes safe on one path, because nothing in it serialises a roll – that is the lock in section 8, which follows a move as well: measured against the plain handler on the same configuration it kept 800 of 800 records where the plain one kept 526.
How large should maxBytes and backupCount be?
Big enough that the budget covers the window an incident is investigated in, and small enough that the budget fits the disk. The budget is maxBytes times backupCount plus one, and it must exceed what the service writes in that window or the newest lines will be deleted before anyone reads them. The measurements here used 123 to 125-byte lines and 131,072 bytes of budget for 99,560 bytes of records, which is the margin that keeps a race from being confounded with retention.
What does the guard cost per record?
Nothing measurable on local storage with rotation off, because the check is not called: 7.6 microseconds against 7.6 for the standard handler, and 12.5 microseconds with rotation on, against 9.3 for the standard handler rotating, where the check itself costs 2.5 microseconds. On a network mount it is a round trip – 4.400 ms per record straight after a write, against 2.4 microseconds when nothing was written in between – and waiting does not clear it: 8 of 8 checks that waited 5 seconds still paid it. A synchronous write pays the same round trip in the write itself (4.617 ms per record), so the cheap fix is to keep the log local or let an external rotator own the file.
12. What was verified, and what is out of scope
Every figure in this article was rendered from a JSON record that a probe in this article wrote, and the build refuses a token that no record contains; the package’s suite runs green on the same host. What follows is what that does and does not establish.
The blocks are shown as they ran, and the page says which way each one runs. A block of definitions executes and returns; the program is the entry function its file calls from if __name__ == "__main__": at the end. Two blocks execute in their module’s namespace instead: the shared fixture, because it imports the package and its helper name would collide with a bare file of the same name, and the four-writer harness of section 4, which reads its module’s directory from __file__.
Each block is the part of its file that produced the number beside it – the constants, the child processes, the measuring functions – and not the whole file. What is left out is the scaffolding that no figure depends on – each probe’s main(), the shared write() and scratch() that create a directory and save the JSON – and the timing harness behind section 8’s per-record costs, a loop of perf_counter() calls around a handler that the section describes in words. Every block below is checked against the file it is printed from, so an excerpt cannot drift from the code that ran.
| How the block was checked | Blocks |
|---|---|
| a verbatim slice of its source file | 14 of 14 |
| executes standalone, as printed | 12 |
| executes in its module’s namespace | 2 |
| defines names and returns, runs nothing | 14 |
names an entry point behind its file’s __main__ guard | 7 |
- Measured on one host. Linux 6.12.8+, CPython 3.12.16, 2 vCPUs of an Intel(R) Xeon(R) Platinum 8488C, 1,522,164 KiB of memory. Timings are medians of repeated runs on this machine and describe the shape of a cost, not another machine’s number.
- Two mounts, both measured. A virtiofs mount with a 1,048,576-byte block size and a tmpfs mount with 4,096 bytes. Nothing here was measured on ext4, XFS or a real NFS server, and the buffer result in section 5 depends on
st_blksize, which those filesystems set differently. - Every trial is in the record. Tables print medians of three or five runs and the JSON keeps each run, including the ones that disagree, so a reader can see the spread.
- The slow sink is a harness. Its five milliseconds are constructed, not measured from a particular collector; it stands in for any sink that answers in milliseconds.
- The queue is a thread in one process. A
multiprocessing.Queuewould need the record formatted before it is put, and its failure modes are not in this article. - The suite is green, not complete. 40 tests in 3 files cover the two guards and their contracts. The probes themselves are not part of that suite; they are scripts whose records are the test.
- The retention budget is a decision. Where the budget is smaller than the traffic, records are deleted by design – 397 kept of 1,200 in the first four-writer trial of Table 4 – and no handler can keep what the configuration deletes.
Out of scope, restated because it is easy to over-read this article: syslog and journald, the Docker and Kubernetes log drivers, cloud log agents, structured and JSON formatting cost, tracing, Windows event logs, macOS unified logging, multi-host shipping, sampling, and the behaviour of any particular storage appliance.
13. Keep reading on TechBobby
This runbook is about the cost a request timer hides. The closest neighbours are the ones about work that happens on the same thread: httpx AsyncClient in production for a client that blocks the loop while it waits, streaming in FastAPI and Starlette for the response side of the same buffer arithmetic, and pytest-asyncio in CI for the tests that should have caught it.
For the processes that write the lines: Python subprocess deadlocks for the pipe whose 64 KiB is the same kind of buffer, ProcessPoolExecutor in production and Celery production architecture for the workers that share a log path, and Kubernetes pod resources and OOMKilled for the container that ends the process with records still in the queue. The TechBobby Stack is the tooling map these runbooks belong to.
Two free resources from TechBobby: the AI Prompt Pack for engineers and the Zero-Crash Python newsletter – free, one production failure per issue.
