Skip to content
Python project #16Intermediate

Log File Analyzer

Parse web-server logs with regular expressions and report levels, status classes, slow endpoints with percentiles, traffic per hour and top errors.

Estimated time
~3 hours to build
Files
4 files · 242 lines
Technologies
Python 3, re, collections

Introduction

When a website slows down or fails, engineers turn to its logs. This analyzer reads log lines from standard input and produces the summary an engineer would want first, skipping lines it can't understand.

Problem statement

Read lines in two formats — requests ('date time LEVEL METHOD path status 120ms') and messages ('date time LEVEL text'). Count lines by level, requests by status class, and for each endpoint the hits, average, 90th-percentile and maximum response times, sorted by slowest average. Show requests per hour and the most common errors. Report malformed lines by number.

Objectives

  • Parse structured text with named regular-expression groups
  • Aggregate with Counter and defaultdict
  • Compute percentiles
  • Present a multi-section report

Features

  • Request and message line formats
  • Level and status-class counts
  • Endpoint latency with average, p90 and max
  • Requests-per-hour chart
  • Top errors and malformed-line report

Concepts demonstrated

  • Regular expressions
  • Aggregation
  • Percentiles
  • Walrus operator

System architecture

Two compiled patterns, REQUEST and MESSAGE, are tried in turn for each line with the walrus operator. analyse fills Counters for levels, statuses and hours, a defaultdict of response times per endpoint, and a Counter of errors (5xx responses and ERROR messages). percentile uses the nearest-rank method. main prints each section.

Folder structure

TextProject tree
log-file-analyzer/
├── README.md
├── main.py
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

main.py

84 lines
Pythonmain.py
"""Log File Analyzer: summarises web-server style logs read from standard input.
Expected line formats:
2026-11-27 09:00:01 INFO GET /home 200 120ms (a request)
2026-11-27 09:05:00 ERROR Database timeout (a message)
Usage: python main.py < server.log
"""
import re
import sys
from collections import Counter, defaultdict
REQUEST = re.compile(r"(?P<day>\d{4}-\d{2}-\d{2}) (?P<time>\d{2}:\d{2}:\d{2}) (?P<level>[A-Z]+) "
r"(?P<method>GET|POST|PUT|DELETE) (?P<path>\S+) (?P<status>\d{3}) (?P<ms>\d+)ms$")
MESSAGE = re.compile(r"(?P<day>\d{4}-\d{2}-\d{2}) (?P<time>\d{2}:\d{2}:\d{2}) (?P<level>DEBUG|INFO|WARN|ERROR) (?P<text>.+)$")
def percentile(values: list[int], p: float) -> int:
ordered = sorted(values)
index = min(len(ordered) - 1, round(p / 100 * (len(ordered) - 1)))
return ordered[index]
def analyse(lines: list[str]) -> dict:
levels, statuses, per_hour = Counter(), Counter(), Counter()
times: dict[str, list[int]] = defaultdict(list)
errors, malformed = Counter(), []
for number, raw in enumerate(lines, 1):
line = raw.strip()
if not line:
continue
if m := REQUEST.match(line):
levels[m["level"]] += 1
statuses[m["status"][0] + "xx"] += 1
times[f"{m['method']} {m['path']}"].append(int(m["ms"]))
per_hour[m["time"][:2]] += 1
if m["status"].startswith("5"):
errors[f"{m['status']} on {m['path']}"] += 1
elif m := MESSAGE.match(line):
levels[m["level"]] += 1
if m["level"] == "ERROR":
errors[m["text"]] += 1
else:
malformed.append(number)
return {"levels": levels, "statuses": statuses, "per_hour": per_hour, "times": times,
"errors": errors, "malformed": malformed}
def main() -> None:
lines = sys.stdin.read().splitlines()
r = analyse(lines)
requests = sum(len(v) for v in r["times"].values())
print(f"Lines read: {len(lines)} requests: {requests} malformed: {len(r['malformed'])}")
if r["malformed"]:
print(f" malformed line numbers: {', '.join(map(str, r['malformed']))}")
print("\nBy level")
for level in ("DEBUG", "INFO", "WARN", "ERROR"):
if r["levels"][level]:
print(f" {level:<6}{r['levels'][level]:>4}")
print("\nStatus classes")
for status, count in sorted(r["statuses"].items()):
print(f" {status} {count:>4} ({count / requests:.0%})")
print("\nEndpoints (slowest average first)")
print(f" {'Endpoint':<22}{'Hits':>5}{'Avg ms':>8}{'p90 ms':>8}{'Max ms':>8}")
stats = [(path, len(ms), sum(ms) / len(ms), percentile(ms, 90), max(ms)) for path, ms in r["times"].items()]
for path, hits, avg, p90, worst in sorted(stats, key=lambda s: -s[2]):
print(f" {path:<22}{hits:>5}{avg:>8.0f}{p90:>8}{worst:>8}")
print("\nRequests per hour")
for hour in sorted(r["per_hour"]):
print(f" {hour}:00 {r['per_hour'][hour]:>3} {'#' * r['per_hour'][hour]}")
print("\nTop errors")
if not r["errors"]:
print(" none")
for text, count in r["errors"].most_common(3):
print(f" {count} x {text}")
if __name__ == "__main__":
main()

What each file does

main.py
The log patterns, the analysis pass, the percentile helper and the report.

How to run it

Run

Terminal
python main.py # use python3 on Linux / macOS

Test against the expected output

Terminal
python main.py < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | python main.py > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
Lines read: 18 requests: 12 malformed: 2
malformed line numbers: 11, 17
By level
DEBUG 1
INFO 9
WARN 2
ERROR 4
Status classes
2xx 8 (67%)
3xx 1 (8%)
4xx 1 (8%)
5xx 2 (17%)
Endpoints (slowest average first)
Endpoint Hits Avg ms p90 ms Max ms
GET /checkout 1 3000 3000 3000
POST /checkout 2 1650 2500 2500
GET /products 3 543 980 980
POST /cart 1 210 210 210
GET /home 3 108 120 120
GET /login 1 40 40 40
GET /missing 1 15 15 15
Requests per hour
09:00 5 #####
10:00 4 ####
11:00 3 ###
Top errors
2 x Database timeout
1 x 500 on /checkout
1 x 503 on /checkout
Input
2026-11-27 09:00:01 INFO GET /home 200 120ms
2026-11-27 09:00:05 INFO GET /products 200 340ms
2026-11-27 09:01:12 INFO POST /cart 201 210ms
2026-11-27 09:02:30 WARN GET /products 200 980ms
2026-11-27 09:03:00 DEBUG cache warmed in 85ms
2026-11-27 09:05:00 ERROR Database timeout
2026-11-27 09:05:01 ERROR GET /checkout 500 3000ms
2026-11-27 10:10:10 INFO GET /home 200 95ms
2026-11-27 10:11:00 INFO GET /login 302 40ms
2026-11-27 10:12:45 INFO GET /missing 404 15ms
this line is not a log entry
2026-11-27 10:20:00 ERROR Database timeout
2026-11-27 10:20:02 ERROR POST /checkout 503 2500ms
2026-11-27 11:00:00 INFO GET /products 200 310ms
2026-11-27 11:01:00 INFO POST /checkout 200 800ms
2026-11-27 11:30:00 WARN Disk usage at 85%
27/11/2026 11:31 INFO wrong date format
2026-11-27 11:45:00 INFO GET /home 200 110ms

Testing

  • Run python main.py < tests/sample-input.txt and compare with tests/expected-output.txt.
  • Lines 11 and 17 are reported as malformed.
  • GET /checkout (3000 ms) and POST /checkout (average 1650 ms) are the slowest endpoints.
  • 'Database timeout' is the most common error, appearing twice.

Common errors

Lines with extra spaces aren't matched

Strip lines first and keep patterns anchored but flexible about whitespace.

Percentiles are off by one

Compute the index on the sorted list as round(p / 100 * (n - 1)).

Possible improvements

  • Accept log files as command-line arguments
  • Output the report as JSON for dashboards
  • Alert when the error rate passes a threshold

Additional challenges

  1. 1Detect bursts: more than 3 errors within one minute.
  2. 2Group endpoints with ids (/user/17, /user/42) into /user/{id}.
  3. 3Compare two log files and show which endpoints got slower.

Built and tested it yourself? Mark it to update your dashboard.