Build a Simple Log Graph in Python
Create a basic one-dimensional bar chart from log lines by counting occurrences of leading numeric keys.
Python code
43 linesimport 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
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
- Use `collections.Counter` to tally counts more succinctly
- 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
More from Git + Python
- Amend Last Commit Message in Python easy
- Bisect Good Bad Automation Script in Python easy
- Bump Semantic Version Git Tag in Python easy
- Count Unique Contributors from Git Shortlog in Python easy
- Create a Mock GitHub Release API in Python for Testing gh CLI easy
- Detect Merge Conflict Markers in a File with Python easy
Keep learning
Related tutorials and quizzes for this topic.