AW Dev Rethought

⚖️ There are two ways of constructing a software design: one way is to make it so simple that there are obviously no deficiencies - C.A.R. Hoare

🧩 Python Automation Recipes – 🧹 Log File Cleaner


Description:

📌 Introduction

Log files grow silently — until they start eating disk space or slowing systems down. Manually cleaning them is error-prone and often forgotten.

This automation recipe shows how to delete or archive old log files based on age, using a simple Python script you can run manually or schedule. This is a very common production automation used in servers, local dev machines, and CI systems.


🔎 Explanation

  • The script scans a target log directory for files with a .log extension.
  • For each file, it checks the last modified time.
  • If the file is older than a defined number of days:
    • it can be deleted, or
    • moved to an archive folder for later reference.
  • All logic is built using Python’s standard library.

This pattern is safe, predictable, and easy to extend.


✅ Key Takeaways

  • 🧹 Automatically clean up old log files.
  • ⏱️ Control retention by number of days.
  • 📦 No dependencies — pure Python automation.

Code Snippet:

from pathlib import Path
from datetime import datetime, timedelta
import shutil

# --- Step 1: Configuration ---

# Folder containing log files
LOG_FOLDER = Path("")  # 🔁 change this

# Archive folder (used if ARCHIVE_OLD_LOGS = True)
ARCHIVE_FOLDER = LOG_FOLDER / "archive"

# Number of days to keep logs
RETENTION_DAYS = 7

# Action mode: True = archive, False = delete
ARCHIVE_OLD_LOGS = True

# Ensure archive directory exists if needed
if ARCHIVE_OLD_LOGS:
    ARCHIVE_FOLDER.mkdir(exist_ok=True)

# --- Step 2: Calculate cutoff date ---
cutoff_date = datetime.now() - timedelta(days=RETENTION_DAYS)

# --- Step 3: Process log files ---
for log_file in LOG_FOLDER.glob("*.log"):

    # Get last modified time
    last_modified = datetime.fromtimestamp(log_file.stat().st_mtime)

    # Check if file is older than retention period
    if last_modified < cutoff_date:

        if ARCHIVE_OLD_LOGS:
            destination = ARCHIVE_FOLDER / log_file.name
            shutil.move(str(log_file), str(destination))
            print(f"📦 Archived: {log_file.name}")
        else:
            log_file.unlink()
            print(f"🗑️ Deleted: {log_file.name}")

print("\n✅ Log file cleanup completed.")

Link copied!

Comments

Add Your Comment

Comment Added!