Parsing Log Files That Contain Malformed and Truncated Lines

You point grep at a log file and get back a line that's half a timestamp, no level, and a message that cuts off mid-word. Or you pipe the output of a crashed daemon into a parser and it chokes on a null byte. This happens more than you'd think when you're pulling logs from a home server that's been running for eight months without a reboot, or when a USB drive dies mid-write to your Graylog ingest node. The data is there, but it's not clean, and most one-liners will either crash or silently drop the whole file.

The script below handles that situation. It reads a log file line by line, matches each line against a strict regex, prints the parsed fields as tab-separated values to stdout, and sends anything that doesn't match to stderr with its line number. It exits cleanly when piped to head, it survives binary garbage in the middle of the file, and it gives you a summary count at the end so you know exactly how much data you lost versus how much you kept.

Verified terminal output of parse_log.py — real test runs in a clean, network-isolated container.

The regex

The pattern is three capture groups anchored to the full line:

^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) (\w+) (.+)$

Group 1 is an ISO-style timestamp: four digits, hyphen, two digits, hyphen, two digits, space, then two-colon-two-colon seconds. Group 2 is a single word, which in practice is the log level: INFO, WARN, ERR, DEBUG. Group 3 is the message body, at least one character long. The $ anchor means nothing can trail after the message except the newline we strip before matching.

The .+ in group 3 is what rejects truncated lines. If a line reads 2024-03-15 08:01:04 ERR with no message after the level, the regex won't match because there's nothing left for .+ to grab. That line goes to stderr as a skip, and you see the first 80 characters of what it looked like so you can judge whether it was a real error that got cut short or just a partial write from a power blip.

Why it's anchored end to end

Two details make this stricter than it looks. The pattern is both anchored with ^ and $ and applied through match(), so a line has to conform from its first character to its last. An unanchored search() would happily light up on a timestamp buried in the middle of a garbage line and hand back a half-parsed fragment; here, if anything trails after the message or sits before the timestamp, the whole line is rejected and reported instead. The (\w+) for the level is equally deliberate: it accepts INFO, WARN, ERR, DEBUG and refuses a level containing a space or punctuation, which is precisely the shape of a corrupted line you want to catch rather than swallow.

Reading the file

The script opens the file with errors='replace'. This is not a cosmetic choice. If your log has a stray 0xFF byte from a disk controller hiccup, Python won't throw a UnicodeDecodeError and kill the whole run. The bad byte gets replaced with U+FFFD, the line fails the regex, and it lands in your skip list. You keep processing the rest of the file instead of losing everything after byte 4,217.

The OSError catch handles the case where the path doesn't exist or you don't have read permission. It prints a one-line error to stderr and exits with code 1. No traceback, no multi-line PermissionError: [Errno 13]... noise cluttering your terminal while you're already trying to figure out what went wrong.

The loop and the pipe

The main loop enumerates lines starting at 1, because that's the number you'll reference when you tell a colleague "line 47 was garbage." For each line it strips the trailing newline, runs LOG_RE.match, and either prints the three groups tab-separated to stdout or prints a [SKIP line N] diagnostic to stderr with a truncated preview of the offending content.

The BrokenPipeError catch at the end of the loop is what lets you run python3 parse_log.py big.log | head -2 without getting a stack trace dumped into your terminal. When head closes the read end after two lines, Python raises BrokenPipeError on the next print call. The script catches it and exits 0. You got your two lines; no error noise, no "Exception ignored in:" warning.

Why skips go to stderr

There is a reason the clean data and the diagnostics split across two streams. Standard output carries only the tab-separated rows, so redirecting stdout writes a file that contains nothing but usable records — no skip previews, no summary line polluting the dataset. Everything a human needs to see, the [SKIP line N] previews and the final count, goes to stderr, which stays on your terminal even while you redirect stdout elsewhere. That separation is what makes the script composable: pipe stdout into awk, cut, or a spreadsheet import without the diagnostics getting in the way, and still get told exactly what was dropped and where.

What the verification showed

I ran this in a clean Ubuntu container against six test files covering normal logs, empty files, paths with spaces, large files piped to head, binary content, missing files, and missing arguments. All 19 assertions passed, zero failures. A few highlights from the actual output:

A normal log with interleaved garbage text, an empty line, and a truncated ERR entry (no message after the level) produced four valid lines on stdout:

2024-03-15 08:01:02 INFO     Service started on port 8080
2024-03-15 08:01:03 WARN     Disk usage at 91%
2024-03-15 08:01:04 ERR   Connection refused to db-primary
2024-03-15 08:01:05 INFO     Request handled in 42ms

The three bad lines went to stderr. The summary line read: summary: 4 ok, 3 skipped. That tells you at a glance that 43% of this file was unusable, which is useful information when you're deciding whether to re-pull the log from the source machine.

A file path containing spaces (/tmp/testdata/my logs dir/app log.txt) parsed both valid lines without issue. No quoting gymnastics needed beyond the standard shell quotes.

Piping a large file into head -2 produced exactly two lines and exited cleanly:

2024-01-01 00:00:00 INFO     Line one
2024-01-01 00:00:01 INFO     Line two

A file with a binary blob in the middle parsed the lines before and after it, skipped the binary line to stderr, and continued. No crash, no partial output.

No arguments produced exit code 2 with a usage string. A missing file produced exit code 1: error: cannot read '/tmp/testdata/does_not_exist.log': No such file or directory.

The script

#!/usr/bin/env python3
"""Parse structured log lines; skip malformed, report line numbers."""
import sys, re

LOG_RE = re.compile(r'^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) (\w+) (.+)$')

def main():
    if len(sys.argv) < 2:
        print("usage: parse_log.py <logfile>", file=sys.stderr)
        sys.exit(2)
    path = sys.argv[1]
    try:
        with open(path, 'r', errors='replace') as f:
            lines = f.readlines()
    except OSError as e:
        print(f"error: cannot read '{path}': {e.strerror}", file=sys.stderr)
        sys.exit(1)
    if not lines:
        print("error: input is empty", file=sys.stderr)
        sys.exit(1)
    good = bad = 0
    try:
        for i, raw in enumerate(lines, 1):
            m = LOG_RE.match(raw.rstrip('\n'))
            if m:
                good += 1
                print(f"{m.group(1)}\t{m.group(2)}\t{m.group(3)}")
            else:
                bad += 1
                print(f"[SKIP line {i}] {raw.rstrip()[:80]}", file=sys.stderr)
    except BrokenPipeError:
        sys.exit(0)
    if bad:
        print(f"summary: {good} ok, {bad} skipped", file=sys.stderr)

if __name__ == '__main__':
    main()

How to use it

Basic parse. Valid lines go to your terminal, skip diagnostics go to stderr:

python3 parse_log.py /var/log/myapp/app.log

Send only the parsed output to a file, keep the skip list visible on screen so you can check what was dropped:

python3 parse_log.py /var/log/myapp/app.log > parsed.tsv

Preview the first five lines of a large log without processing the whole thing into memory:

python3 parse_log.py /tmp/testdata/big.log | head -5

Feed it a file sitting in a directory with spaces in the name:

python3 parse_log.py '/tmp/testdata/my logs dir/app log.txt'

The tab-separated output is ready for awk, cut, or a quick import into a spreadsheet if you need to hand the parsed data to someone who isn't going to read raw logs.

Where this stops being enough

This is a line-oriented parser, and that boundary is worth stating plainly. It assumes one line equals one log event. If your application writes multi-line entries — a stack trace, a pretty-printed JSON blob, a message that wraps across several lines — each physical line is judged on its own, and most of them land in the skip list rather than being reassembled into the record they belong to. For those logs you want a stateful parser that tracks whether it is inside a continuation block; this script is not that, and pretending otherwise would be worse than skipping.

It also refuses to guess at what was lost. A truncated ERR with no message is reported as skipped, not repaired — the script will not invent the missing half of a line for you. That is a feature: you get an exact line number to go back and investigate, instead of a parser quietly fabricating plausible-looking data that looks authoritative in your downstream report. And the 80-character cap on each skip preview means one pathological line cannot flood stderr; you see enough to recognise it without drowning in it.


Luke Keam
Spot a bug or want a custom utility built? I'd love to hear from you. Get in touch
Luke Keam | techgeek.biz