The same program, two orders#
The fixture prints two steps to stdout, an error to stderr, and then a third step.
import sys
print("step 1 connect")
print("step 2 query")
print("ERROR: query failed", file=sys.stderr)
print("step 3 cleanup")
In a terminal, the lines appear in the order of the source. Redirected with python3 b.py > all.log 2>&1, the file holds:
ERROR: query failed
step 1 connect
step 2 query
step 3 cleanup
A reader of that file concludes that the query failed before the program connected. Python's documentation explains it: when interactive, stdout is line-buffered, and otherwise it is block-buffered like a regular text file, while stderr is line-buffered in both cases. sys.stdout The three stdout lines stayed in the buffer until the program ended.
python3 -u, or PYTHONUNBUFFERED=1, gives the source order in the file. Run with Python 3.12.
Other causes of the same symptom#
| Cause | How to tell |
|---|---|
| Block buffering in one process | Lines of one stream come in large groups. Disabling the buffer changes the order |
| Two processes or threads writing | Buffering off, and order still varies between runs |
| A collector that reads the streams separately | The program's own file is in order, and the collected log is not |
| Different clocks on two hosts | Order by timestamp contradicts a known cause and effect |
| The program really did it in that order | Timestamps taken at the moment of writing agree |
The second row means that turning buffering off removes one explanation, and does not make the order a proof.
Make the order readable#
Put the time in the line when the event happens, in UTC with at least milliseconds, and give each request an ID. A timestamp that the collector adds tells you when the line arrived.
import logging, time
logging.Formatter.converter = time.gmtime
logging.basicConfig(format="%(asctime)s.%(msecs)03dZ %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S", level=logging.INFO)
When you cannot change the program, capture the streams apart and send both: cmd >out.log 2>err.log. You lose the order between them, and nobody is misled about it.
Write it into the handoff#
State how the log was captured: terminal, redirect or collector, and whether the program buffers. If the order matters to your conclusion, name the evidence for it: "Both lines carry the program's own time: 09:14:02.118 connect, 09:14:02.640 error."
Without such a time, write "order not established". The receiver can then look for it instead of building on it.
Worked example#
This example is fictional. A handoff says that the importer fails before it reads its configuration, and Ben is asked to fix startup. The log is a redirect from a Python job. With PYTHONUNBUFFERED=1 the error comes after loaded config and opened batch 7. The question changes from startup to batch 7, whose file has a malformed row.
A buffer can also make lines disappear, as an empty log after a kill shows. Return to handing over evidence.