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.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 15 views 0 copies

Python code

36 lines
Python 3.9+
import 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

stdout
INFO: Server started
ERROR: Connection refused
DEBUG: Retrying in 3s
ERROR: Timeout occurred
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

  1. Use `collections.deque(..., maxlen=n)` to read only the tail without loading the entire file.
  2. 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

Run this sample

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

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.