Write a few dozen lines of Python with re and Counter to turn messy log files into an error ranking table you can bring into customer meetings.

Key takeaways

  • Counting raw error messages directly is almost useless: order numbers, millisecond values, and various IDs make every line its own group.
  • The standard approach: use named-group regexes to extract fields, use re.sub to replace variable parts, and use Counter.most_common to sort.
  • When there are too many log patterns to hand-write rules, Drain3 can automatically learn templates and replace differing tokens with <*>.

According to the Python logging documentation,

Logger.exception()

writes the stack trace along with the message. So log files sent by customers are rarely as tidy as one error per line: one error may be followed by ten lines of traceback, and those lines neither start with a timestamp nor have a log level.

There is a second problem. Error messages usually contain order numbers, millisecond values, and memory addresses. If you count raw messages directly, the same timeout error gets split into hundreds of groups each appearing once, and the table's conclusion is: no error stands out.

For a Forward Deployed Engineer (FDE), when a customer sends logs, the first question is almost always "which error is the most frequent?". This guide uses only the standard library

re

and

collections.Counter

to write a small Python script that answers this question. You need Python 3 and a log file to practice on.

First, prepare a sample log

The format below is a fictional, simplified example. Customers' real logs will differ, but the structure is usually similar: structured fields at the start of the line, free text at the end. Save it as

app.log

:

2026-11-03 09:14:22 [ERROR] [payments] Timeout calling bank API order=84213 after 3000ms
2026-11-03 09:14:25 [INFO] [api] GET /orders/84213 200
2026-11-03 09:14:31 [ERROR] [payments] Timeout calling bank API order=90117 after 3012ms
2026-11-03 09:15:02 [ERROR] [worker] Failed to process job 5521
Traceback (most recent call last):
  File "worker.py", line 42, in run
KeyError: 'customer_id'
2026-11-03 09:15:40 [ERROR] [worker] Failed to process job 5530
Traceback (most recent call last):
  File "worker.py", line 42, in run
KeyError: 'customer_id'

Note that six lines do not start with a timestamp. They are the tracebacks of the two failed jobs 5521 and 5530, and each block must follow the line above it.

If the customer uses Python's default configuration, the format is simpler. According to the logging documentation, the default format is

severity:logger name:message

. The standard levels run from DEBUG to CRITICAL, so the filtering list is ready-made.

Step 1: Write a regex you can still understand three months later

Create a new file

logtop.py

. Write the regex as a raw string (with the

r

prefix) so Python does not process backslash sequences like

\d

before the regex engine sees them. Then use

re.VERBOSE

to split the pattern into commented sections:

import re
from collections import Counter

LINE = re.compile(r"""
    ^(?P<ts>\d{4}-\d{2}-\d{2}\ \d{2}:\d{2}:\d{2})\s+  # 时间戳
    \[(?P<level>.+?)\]\s+                             # 日志级别
    \[(?P<logger>.+?)\]\s+                            # logger 名称
    (?P<msg>.*)$                                      # 自由文本消息
""", re.VERBOSE)

Each

(?P<name>...)

is a named group. This is Python-specific syntax that lets you extract fields by name rather than by position. The pattern is compiled once at the top of the file with

re.compile()

.

re

The documentation notes that this is more efficient when the same expression is run multiple times, and here we are running it over millions of lines.

An easily overlooked detail is the

.+

after

?

. It makes the quantifier non-greedy, matching as few characters as possible. For the sample line above, removing

?

still splits correctly, because the matcher backtracks until the rest of the pattern can match.

The trouble comes when the message itself contains square brackets. Try a log line where the timestamp is followed by

[ERROR] [api] Rejected [role] [admin] for user 7

. The greedy version stops at the farthest

]

that still allows a match, yielding

level

of

ERROR] [api] Rejected [role

,

logger

of

admin

. The non-greedy version stops at the first

]

and correctly returns

ERROR

and

api

。

One more thing to note: VERBOSE mode ignores whitespace, so the space between the date and time must be written as

\

。

Check: run

LINE.match(...)

on the first line in the REPL, call

.groupdict()

, and confirm that

level

of

ERROR

. Then try the log line above whose message contains square brackets.

Step 2: Attach tracebacks to the right error

groupdict()

returns all named groups as a dict, which is exactly what you need to turn a log line into a record. Any line that does not match the pattern is treated as a continuation of the previous record:

def parse(path):
    records = []
    with open(path, encoding="utf-8") as f:
        for raw in f:
            line = raw.rstrip("\n")
            m = LINE.match(line)
            if m:
                rec = m.groupdict()
                rec["trace"] = []
                records.append(rec)
            elif records:
                records[-1]["trace"].append(line)
    return records

Check: the sample file has 11 lines, but you should get 5 records, and the records for jobs 5521 and 5530 each have a three-line

trace

. If you get more than 5, the regex is mistakenly matching traceback lines.

Step 3: Normalize first, then count

This step determines the entire results table.

re.sub

replaces all occurrences of the pattern by default unless you pass the

count

argument, so each rule only needs one call:

RULES = [
    (re.compile(r"0x[0-9a-fA-F]+"), "<HEX>"),
    (re.compile(r"\d+"), "<NUM>"),
]

def normalize(text):
    for pat, placeholder in RULES:
        text = pat.sub(placeholder, text)
    return text

def signature(rec):
    sig = normalize(rec["msg"])
    if rec["trace"]:
        sig += " | " + normalize(rec["trace"][-1].strip())
    return sig

The order of the rules matters: if you replace numbers first,

0x7f3a

becomes

<NUM>x<NUM>f<NUM>a

, and the HEX rule catches nothing. After this step, both timeout log lines in the sample file become

Timeout calling bank API order=<NUM> after <NUM>ms

。

The tracebacks merged in Step 2 come into play here. In the sample file, the message "Failed to process job" does not say why the job failed; the reason is in the last line of the traceback:

KeyError: 'customer_id'

。

Append that line to the signature, and the two worker errors become

Failed to process job <NUM> | KeyError: 'customer_id'

. Later, the same message appearing with a different exception will form its own group instead of being mixed together.

Do the math with the sample file. Counting directly, the four ERROR lines produce four groups each appearing once, revealing nothing. After normalization there are only two groups, each appearing twice. With a real log of tens of thousands of lines, this difference is the difference between a useless table and a to-fix list.

Step 4: Sort, and mark where and when each error started

Counter

is a dict subclass for counting hashable objects, and signature strings are hashable.

most_common(n)

returns the n most common elements and their counts, ordered from most to least. While counting, the script also records the earliest timestamp for each signature and the logger of that occurrence:

if __name__ == "__main__":
    records = parse("app.log")
    errors = [r for r in records if r["level"] in ("ERROR", "CRITICAL")]
    counts = Counter()
    first = {}
    for r in errors:
        sig = signature(r)
        counts[sig] += 1
        if sig not in first or r["ts"] < first[sig][0]:
            first[sig] = (r["ts"], r["logger"])
    for sig, n in counts.most_common(10):
        ts, logger = first[sig]
        print(f"{n:>6}  {ts}  [{logger}]  {sig}")

Comparing

r["ts"]

as strings works only because the sample format is ordered from year down to seconds; if the customer's log uses a different time notation, convert to

datetime

before comparing. This is also a simplified version: each signature keeps only the logger of its first occurrence, and if the same error comes from multiple loggers, you need a separate

Counter

to count loggers.

Run

python3 logtop.py

. Check: the output should look like this:

     2  2026-11-03 09:14:22  [payments]  Timeout calling bank API order=<NUM> after <NUM>ms
     2  2026-11-03 09:15:02  [worker]  Failed to process job <NUM> | KeyError: 'customer_id'

If you see four lines, the normalization rules did not run or are in the wrong order. If the worker errors split into two groups, check whether Step 2 attached the tracebacks to the right records.

A few mistakes that let the numbers mislead you

Forgetting the raw string is the most common pitfall. Without the

r

prefix, partially recognized escape sequences like

\b

are interpreted by Python first, and the regex silently matches the wrong content without raising an error. Keeping the greedy mode for bracketed fields is equally dangerous; the

[role] [admin]

line in Step 1 is the example.

Harder to spot is over-normalization.

\d+

The rule turns

HTTP 502

and

HTTP 404

into the same signature, but to the customer these are two completely different problems. If the signature at the top of the table looks too generic, open a few raw records and read them before drawing conclusions.

When hand-written regexes are not enough

With only one or two customer services, a hand-written rule set works well. When logs come from dozens of services with different formats,

RULES

The list will grow faster than you can maintain it. That's when you should look at Drain3, an open-source library that learns log templates from raw logs as they stream in.

Drain's idea is close to the code you just wrote. The algorithm stores learned patterns in a parse tree, replacing unmatched tokens with wildcards

<*>

, just like

<NUM>

standing in for an order number.

The Drain3 documentation also recommends feeding in only the free-text portion, without timestamps or hostnames, so the regex from step 1 is still useful for splitting out the

msg

field first.

Bring the top errors table into meetings

Walking into a first meeting with a top 10 errors table gives you something concrete to open with: this error occurs most often, comes from this logger, started at this time, and the root cause is on the last line of the traceback. Write the script so it can be reused by changing only the file path and line regex, since every customer's log format is different.

If you're targeting an FDE role, put the script on GitHub along with a redacted sample log, and describe it on your resume with results: how many log lines it processed, and how many error groups before and after normalization.

When reading job postings, watch for items that mention handling production incidents or customer issues: that's exactly when you can bring up this tool in interviews.

The next time a customer sends a few hundred MB of log files with a note saying "the system is really slow," you'll already have an answer backed by numbers before the second call even starts.

Was this article helpful?

Thanks for your feedback!

Next on the roadmap · Phase 1: Foundational understanding. Catch the customer's bad JSON on the client side, then test offline by swapping only the transport layer, so the same client can call the real API and run offline tests without changing a single line of code.