Module 22 · Lesson 12 of 64

Logging, mmap and common mistakes

Configure level-aware logging with handlers and rotation, scan large files with mmap, and diagnose the recurring file and process mistakes.

  • Beginner to advanced
  • 10 min read
  • 14 min lab
What you will need

Ubuntu 24.04 (WSL2, a VM, or a container) with Python 3.11 or newer (Ubuntu 24.04 ships 3.12); a terminal; no board needed for this lesson

Your place in the module
By the end you can 3 objectives
  • Configure level-aware logging with handlers, formatters, and rotation, and decide between log and print.
  • Use mmap to lazily scan large files and avoid its truncation and lifetime hazards.
  • Diagnose the recurring file, subprocess, and logging failures by their symptoms.
Video coming soonLogging, mmap and common mistakes
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Running external tools with subprocess
  • Pass subprocess arguments as a list; shell=True hands your string to a shell and invites injection.
  • A Linux pipe holds 64 KiB by default; wait() before draining stdout can deadlock, so use communicate().
  • run(timeout=...) kills the child, but communicate(timeout=...) and wait(timeout=...) only raise and leave it running, so kill and reap it afterward.
01

logging: levels, handlers, and formatters

5 min read

The third lesson on this topic showed how to run and stream external tools without deadlocking. This lesson answers how to log what your tools do, scan huge logs with mmap, and fix the recurring mistakes across all of this.

Start with the difference. print writes text to stdout, with no severity, no timestamp, and no way to route it. A lets you keep detailed traces in a file while the console stays quiet, and change your mind later without editing code. The five standard levels, with their numeric values, are DEBUG (10), INFO (20), WARNING (30), ERROR (40), and CRITICAL (50). A message passes only if its level is at or above the threshold that is set.

The quickest setup is basicConfig, which configures the root logger:

python
import logging

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
log = logging.getLogger(__name__)
log.info("flashing %s", "fw.bin")
log.warning("boot count is %d", 3)

Two habits in that snippet matter. First, logging.getLogger(__name__) names the logger after the module, so in devkit/flash.py the logger is devkit.flash. Loggers form a hierarchy by dotted name, and a record propagates up to its ancestors' handlers, which is how one configuration covers a whole package. Second, pass values as arguments (log.info("flashing %s", name)) rather than building the string yourself; the formatting then happens only if the message will actually be emitted. One gotcha: basicConfig does nothing if the root logger already has handlers, which is why a second call in a test or a notebook appears to be ignored; pass force=True to reconfigure.

For a real tool you configure handlers explicitly. A is the destination, and a formatter shapes the text. There are two gates, and both must pass: the logger's level filters first, then each handler's level filters again. A logger set to DEBUG with a handler set to WARNING emits only WARNING and above through that handler. This two-gate design is what lets one logger feed a verbose file and a quiet console at the same time:

python
import logging
from logging.handlers import RotatingFileHandler

log = logging.getLogger("devkit")
log.setLevel(logging.DEBUG)

console = logging.StreamHandler()          # stderr by default
console.setLevel(logging.INFO)
console.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))

fileh = RotatingFileHandler("devkit.log", maxBytes=1_000_000,
                            backupCount=5, encoding="utf-8")
fileh.setLevel(logging.DEBUG)
fileh.setFormatter(logging.Formatter(
    "%(asctime)s %(levelname)s %(name)s: %(message)s"))

log.addHandler(console)
log.addHandler(fileh)

StreamHandler() writes to stderr, not stdout, which is the right default: your tool's real output stays on stdout for pipes, and diagnostics go to stderr. RotatingFileHandler solves the log that grows forever: when the file reaches maxBytes, it is renamed to devkit.log.1, older backups shift along, and a fresh file starts, keeping at most backupCount old files. TimedRotatingFileHandler rotates on a schedule instead, such as when="midnight". One caveat: rotation is designed for a single process; if several processes write one file, use a QueueHandler feeding one writer, or rotate externally.

For anything beyond a small script, put the configuration in data, not code. logging.config.dictConfig takes a dictionary, which you can load from JSON or build in one place:

python
import logging.config

logging.config.dictConfig({
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "plain": {"format": "%(levelname)s: %(message)s"},
        "full": {"format": "%(asctime)s %(levelname)s %(name)s: %(message)s"},
    },
    "handlers": {
        "console": {"class": "logging.StreamHandler",
                    "level": "INFO", "formatter": "plain"},
        "file": {"class": "logging.handlers.RotatingFileHandler",
                 "level": "DEBUG", "formatter": "full",
                 "filename": "devkit.log",
                 "maxBytes": 1000000, "backupCount": 5},
    },
    "loggers": {
        "devkit": {"level": "DEBUG", "handlers": ["console", "file"]},
    },
})

disable_existing_loggers=False keeps loggers that modules already created at import time; the default True silences them, a surprise worth knowing. The older fileConfig reads an ini-style file and still works, but dictConfig is the current recommendation. And if you log before configuring anything, Python uses a last-resort handler that writes WARNING and above to stderr, so early messages are not silently lost.

Step by stepThe journey of one log record
  1. Call: log.info creates a LogRecord with the message, level, time, and module.

  2. Logger gate: the record passes only if its level meets the logger's effective level.

  3. Handler gates: each attached handler checks the record against its own level.

  4. Format: the handler's formatter renders the record into text.

  5. Emit: the handler writes the text to its stream or file.

  6. Propagate: unless stopped, the record also travels to ancestor loggers' handlers.

Never log secrets

Logs outlive the run: they are copied, shipped to dashboards, and read by people who should not see credentials. Never log passwords, API tokens, private keys, or full connection strings with credentials. Log a fingerprint or a redacted form instead, and review what your DEBUG lines print before enabling them in production.

On a board, logging has a physical cost. Flash storage wears with every write, so a DEBUG-level file log on the device can shorten its life; keep verbose logs on the host, log to a tmpfs, or rate-limit. And if the root filesystem is read-only, point the file handler at a writable partition or drop the file handler entirely.

The logger hierarchyrootdevkitlevel DEBUGdevkit.flashrecord propagates upconsole handlerattached, INFO, stderrrotating fileattached, DEBUG, maxBytesrootdevkitlevel DEBUGdevkit.flashrecord propagates upconsole handlerattached, INFO, stderrrotating fileattached, DEBUG, maxBytes
The logger hierarchy: root, devkit, and devkit.flash, with console and rotating-file handlers attached to devkit.
02

mmap and the edge cases of paths

5 min read

A is what the mmap module exposes. Open the file in binary, then map it:

python
import mmap

with open("boot.log", "rb") as f:
    with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm:
        i = mm.find(b"kernel panic")
        if i != -1:
            print(mm[i:i + 200].decode("utf-8", errors="replace"))
        last = mm.rfind(b"error")

Length 0 means the whole file. The mapping behaves like a bytes object: find, rfind, slicing, and indexing all work, and mm[i] is an integer byte. Nothing is read up front. The kernel loads a page only when you first touch it, through a page fault, and evicts pages under memory pressure. That makes mmap excellent for random access and repeated scans of a huge file: you pay only for the regions you actually read, and the page cache is shared with every other process mapping the same file. For a single sequential pass, chunked reads are just as good and simpler.

Find which region an address falls in below:

A typical x86-64 layout for the reader process, with ASLR shifting these addresses on every run. The 4 MiB mapping of boot.log occupies 0x7f3c80000000 through 0x7f3c803fffff, in the wide gap between the heap below and the stack above. Entering 0x7f3c80001000 lands in that mapping at offset 4096, the second 4 KiB page of the file, which is exactly the page the kernel faults in when the program first touches it.

  • regions: [{"name": "Text", "start": "0x555555555000", "size": "0x1000", "detail": "Machine code of the reader binary, mapped read-only and executable"}, {"name": "Heap", "start": "0x555555559000", "size": "0x21000", "detail": "Small allocations; grows upward as brk is extended"}, {"name": "boot.log mapping", "start": "0x7f3c80000000", "size": "0x400000", "detail": "4 MiB of boot.log mapped read-only by mmap with length 0; a page is read only on first touch"}, {"name": "Stack", "start": "0x7ffffffde000", "size": "0x21000", "detail": "Grows downward from near the top of user space; one frame per active call"}]

The lifetime rules are where people get burned. On POSIX, the mapping stays valid even after you close the file descriptor; the mapping holds its own reference to the file. But the mmap object itself must stay alive: after mm.close(), any access raises ValueError. An empty file cannot be mapped at all and raises ValueError immediately, so check the size first. ACCESS_READ is read-only; ACCESS_WRITE requires the file opened "r+b" and writes go through to the file; ACCESS_COPY gives you private copy-on-write changes that never reach the disk. On Windows the rules differ, notably that an empty file cannot be mapped and the file cannot be resized while mapped, so test on every platform you ship to.

Going deepermmap hazards: truncation and durability

Two failure modes deserve a place in your mental model. First, if another process truncates the file while you have it mapped, touching a page beyond the new end raises SIGBUS, which kills the process by default; a log rotator that truncates in place can do this to your reader, which is one more reason to prefer rename-based rotation. Second, writes through an ACCESS_WRITE mapping land in the page cache, not necessarily on storage; call mm.flush() to push them, and remember that a crash before the kernel writes back can lose them, exactly as with buffered file writes. The mapping is a view of the page cache, not a durability guarantee.

Paths have their own edges, and most come from the difference between path math and filesystem reality. PurePath and its subclasses PurePosixPath and PureWindowsPath do path computation with no filesystem access at all, which is what you want when a Linux build host computes paths for a Windows machine or vice versa. Path itself is the concrete, platform-appropriate class: PosixPath on Linux, WindowsPath on Windows. Case is the classic trap: Linux filesystems are case-sensitive, so Boot.log and boot.log are different files; Windows and the default macOS filesystem are case-insensitive, so they are the same file. PureWindowsPath even compares case-insensitively to match Windows semantics, while PurePosixPath compares exactly. A tool that globs *.LOG on Linux and finds nothing has met this trap. Symlinks are the second: resolve() expands them, is_symlink() detects them, and rglob refuses to descend through them by default, so a tree walk stays inside the tree you named. When you need the truth about a path, ask the filesystem with stat() rather than trusting the string.

A file mapped into memoryhighStackgrows downmmap regionboot.log pages(free)Heapgrows upData / BSSlowTexthighStackgrows downmmap regionboot.log pages(free)Heapgrows upData / BSSlowText
A process address space with boot.log mapped into it: pages fault in on demand between the heap and the stack.
03

Common mistakes and how to fix them

2 min read

The script hangs with no output. Cause: a piped child filled the 64 KiB pipe buffer while the parent called wait() or communicate() was never reached. Diagnose: ps shows the child sleeping, and strace -p on the parent shows it blocked in wait4 while the child is blocked in write. Fix: drain the pipes with communicate(), or iterate the stream as data arrives; never wait() first with unread pipes.

Mojibake or UnicodeDecodeError on a file that looks fine. Cause: text mode decoded with the wrong encoding, often the locale default on a CI machine. Diagnose: open the file in binary and look at the offending bytes; check what encoding produced them. Fix: pass encoding="utf-8" explicitly, or the encoding the file actually uses; use binary mode for data that is not text.

The command works in your terminal but raises FileNotFoundError in the script. Cause: the script runs with a different environment or working directory, often because env= replaced the environment and dropped PATH, or a cron job starts with a minimal PATH. Diagnose: print shutil.which(tool) and os.environ["PATH"] inside the script. Fix: start env from os.environ.copy(), use absolute program paths, or check with shutil.which first.

The tool failed but the script carried on. Cause: no check=True and no look at returncode. Diagnose: log result.returncode and result.stderr after every call. Fix: check=True plus except subprocess.CalledProcessError, and branch on the code when different failures need different responses.

A filename turned into a command. Cause: shell=True with an f-string that interpolated untrusted text. Diagnose: search the codebase for shell=True and trace where every interpolated value comes from. Fix: pass a list; if a shell is unavoidable, shlex.quote every value.

Log lines are missing. Cause: the logger's level or the handler's level filters them out, or basicConfig ran after handlers already existed and did nothing. Diagnose: print log.getEffectiveLevel() and each handler's level. Fix: set both gates deliberately, and use force=True when reconfiguring.

Scratch files pile up in /tmp. Cause: NamedTemporaryFile(delete=False) without cleanup, or a crash before the cleanup line. Diagnose: list the prefix your tool uses. Fix: prefer TemporaryDirectory, whose cleanup runs even on exceptions, and keep scratch on the right filesystem with dir=.

Recurring failures and fixesScript hangspipe full, wait()firstcommunicate() orstreamUnicodeDecodeErrorwrong encodingencoding= or binaryFileNotFoundErrorPATH lost via env=os.environ.copy()Failureignoredno check=Truecheck=True + exceptFilename rancodeshell=Trueinjectionlist args,shlex.quoteLog linesmissinglevel gates filterset both gatesScratchpiles updelete=False, nocleanupTemporaryDirectorysymptom, cause, fix
The recurring failures of this lesson mapped from symptom to cause to fix.
04

Try it

1 min read

The lab has three parts that build on each other. First, write a pathlib script that walks a directory tree with rglob, classifies each file with stat, and prints a report, replacing a find plus awk one-liner. Second, run an external tool with subprocess.run, capture stdout and stderr, branch on the return code, and handle a timeout cleanly. Third, add level-aware logging with a console handler and a rotating file handler to that same script, then watch what each level gate lets through. The practice pack drills the same skills with shorter questions, including the deadlock and encoding traps. When you finish, the next lesson takes these tools to the hardware: serial ports with pyserial, SSH automation, and sockets.

Key takeaways

  • logging gives you levels, timestamps, and several destinations at once; print gives you none of them.
  • basicConfig is a no-op once the root logger already has handlers, so pass force=True to reconfigure.
  • mmap pages the file in on demand and shares the page cache; length 0 maps the whole file but access after close() raises.
  • Truncating a mapped file can raise SIGBUS in a reader, so prefer rename-based rotation over in-place truncation.
Reflect
  1. Explain to a colleague, in two sentences: configure level-aware logging with handlers, formatters, and rotation, and decide between log and print.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close