OSPython.052: WatchedFileHandler — External Log Rotation and Inode Changes

OSPython.052 — watched log rotation oil painting with BitcoinVersus.tech branding

Open-Source Python • OSPython.052 • 30–40 minutes

When a Linux service keeps a log file open, renaming the file does not automatically redirect its writes. A pathname and an open file descriptor are different things. Python’s WatchedFileHandler detects replacement of the file and reopens it on a subsequent log emission, allowing an external rotation utility to manage retention.

Learning objectives

Distinguish pathnames and inodes, compare application-owned and external rotation, reproduce a rename-and-create sequence in a temporary directory, and verify that later messages reach the new file. Review FileHandler and RotatingFileHandler.

Why an open descriptor survives a rename

On a Unix-like system, renaming a file changes its directory entry, not the identity of an existing open file. A normal file handler can continue appending to the renamed file. Python’s documentation explains that WatchedFileHandler checks device and inode identity before emitting a record. When replacement is detected, it closes the old stream and opens the original pathname again. It does not schedule rotations, compress archives or implement retention. This handler is intended for Unix/Linux rather than Windows.

Tech Tutorials: David McKone demonstrates configuring Linux logrotate. Use the tutorial to understand the external rotation process; the laboratory below does not change system configuration. Original source.
Linux laptop during Linux Day Milano
Kowalski7cc, October 22, 2022, original photograph, CC0. Linux workstation context, not a photograph of the test.

Executable lab: rename, replace, and emit

Run the following example with Python on an authorized Unix-like test system. It creates and removes only its own temporary directory. The two writes bracket an external-style rotation; no privileged commands or live service logs are involved.

import tempfile, pathlib, logging, logging.handlers

with tempfile.TemporaryDirectory() as d:
    p = pathlib.Path(d) / 'app.log'
    old = p.with_suffix('.log.1')
    h = logging.handlers.WatchedFileHandler(p, encoding='utf-8')
    l = logging.getLogger('rotation_lab')
    l.handlers = [h]
    l.propagate = False
    l.setLevel(logging.INFO)
    try:
        l.info('before')
        inode = p.stat().st_ino
        p.rename(old)
        p.touch()
        assert p.stat().st_ino != inode
        l.info('after')
        assert old.read_text() == 'before\n'
        assert p.read_text() == 'after\n'
        print('3 assertions passed')
    finally:
        h.close()
        l.removeHandler(h)

Native execution in Python 3.13.5 on Linux verified three assertions: the replacement inode differs, the archived file contains only before, and the replacement contains only after. The lab models rename-and-create; it does not run logrotate itself.

Operational boundaries

A copy-and-truncate rotation normally retains the original inode, so it is not the same detection mechanism. It can also lose entries during the copy/truncate interval. Check the external utility’s configuration, permissions, ownership and application error handling. Avoid two independent mechanisms rotating the same file. Multiprocess coordination is a separate problem; see multiprocessing logging and handler shutdown and cleanup.

March 2021 administrator discussion about logrotate, open file references and copytruncate. Treat the comments as practical context rather than an approved configuration. Original source.

Exercises and answers

1. Who schedules rotation? 2. Which file receives after? 3. Does a rename alone close the descriptor? 4. Is the handler a guarantee of lossless concurrent rotation?

Answers: 1. An external tool or process. 2. The newly created app.log. 3. No. 4. No; assess permissions, timing and concurrency separately.

Editor’s Note: We volunteer daily to ensure the credibility of the information on this platform is Verifiably True.

BitcoinVersus.Tech publishes technology and financial journalism for informational purposes and does not provide financial, investment, or legal advice.

Leave a Reply