How to Tail and Colorize Error Lines in Python
Reads the last N lines of a log file and prints error lines in red using ANSI color codes.
Python code
36 linesimport sys
import time
from pathlib import Path
def tail_colorize(filename: str, lines: int = 20) -> None:
"""Read last N lines of a file, printing errors in red."""
path = Path(filename)
if not path.exists():
print(f"File '{filename}' not found.", file=sys.stderr)
return
# Read last N lines
content = path.read_text(errors="replace").splitlines()
tail_lines = content[-lines:] if lines > 0 else content
# ANSI color codes
RED = "\033[91m"
RESET = "\033[0m"
for line in tail_lines:
if "error" in line.lower() or "ERROR" in line:
print(f"{RED}{line}{RESET}")
else:
print(line)
if __name__ == "__main__":
# Example usage: create a sample log file and colorize it
sample_log = Path("sample_log.txt")
sample_log.write_text(
"INFO: Server started\n"
"ERROR: Connection refused\n"
"DEBUG: Retrying in 3s\n"
"ERROR: Timeout occurred\n"
"INFO: Shutdown complete\n"
)
tail_colorize(str(sample_log), lines=5)
Output
INFO: Server started
[91mERROR: Connection refused[0m
DEBUG: Retrying in 3s
[91mERROR: Timeout occurred[0m
INFO: Shutdown complete
How it works
The script uses Path.read_text() to load the entire file as a string, splits it into lines, and slices the last N lines. It checks each line for the word "error" (case-insensitive) and wraps matching lines with ANSI escape codes for red text, resetting the color afterward. This makes errors stand out in terminal output without external dependencies.
Common mistakes
- Forgetting to reset ANSI color codes, causing the terminal to stay red.
- Assuming the file is small; reading huge logs into memory can be slow.
- Checking only uppercase 'ERROR' and missing mixed-case variants.
- Not handling missing files gracefully.
Variations
- Use `collections.deque(..., maxlen=n)` to read only the tail without loading the entire file.
- Colorize other severity levels (warnings in yellow, info in green) for richer output.
Real-world use cases
- A DevOps engineer checks a service log after a deployment and wants to instantly spot crash errors.
- A developer debugging a batch job runs a quick tail command to see the last errors before writing a bug report.
- A QA analyst monitors a test runner's output in CI and uses colored errors to quickly identify failing test lines.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.