Build a Simple Log Graph in Python

Create a basic one-dimensional bar chart from log lines by counting occurrences of leading numeric keys.

Easy Python 3.9+ Aug 9, 2026 Git + Python 16 views 0 copies

Python code

43 lines
Python 3.9+
import heapq


def log_graph(log_lines: list[str]) -> str:
    """Build a simple per-line, one-dimensional visual graph from log entries."""
    counts: dict[int, int] = {}
    for line in log_lines:
        tokens = line.split()
        if tokens:
            try:
                idx = int(tokens[0])
            except ValueError:
                continue
            counts[idx] = counts.get(idx, 0) + 1

    if not counts:
        return "No numeric keys found."

    max_count = max(counts.values())
    max_key = max(counts)
    width = len(str(max_key))

    out_lines = []
    for k in sorted(counts):
        bar_len = int(counts[k] / max_count * 30)
        bar = "#" * bar_len
        out_lines.append(f"{k:>{width}}: {bar} ({counts[k]})")

    return "\n".join(out_lines)


if __name__ == "__main__":
    sample_log = [
        "3 request failed",
        "1 ok",
        "3 partial",
        "2 ok",
        "3 ok",
        "1 timeout",
        "2 ok",
        "2 ok",
    ]
    print(log_graph(sample_log))

Output

stdout
1: #### (2)
2: ########## (3)
3: ############ (3)

How it works

This function reads each log line, splits on whitespace, and casts the first token to an integer. It uses a dictionary to count how many times each key appears, then normalizes bar lengths against the maximum count scaled to 30 characters. Sorting keys ensures stable output order. The max_key width calculation aligns labels for readability.

Common mistakes

  • Skipping lines that don't start with an integer instead of handling them gracefully
  • Using `/` for division without converting to int, producing floats in the bar length
  • Forgetting to guard against an empty input dictionary

Variations

  1. Use `collections.Counter` to tally counts more succinctly
  2. Add a character-based legend like `=` instead of `#`

Real-world use cases

  • Summarizing HTTP status code frequencies from server access logs during incident triage
  • Quickly visualizing distribution of log levels (e.g., error codes) across a deployment window
  • Building a lightweight terminal dashboard that charts event counts per minute from streaming logs

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Git + Python

Related tutorials and quizzes for this topic.