Logging File Changes in Real-Time

In this advanced Python example, we will monitor a directory for file changes and log any modifications in real-time. This is useful for:
✅ Detecting changes in important files
✅ Monitoring log files dynamically
✅ Creating a basic file-watching system

We will use the watchdog library to track file changes and log them into a file.


Code Example:

import time
import os
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

# Directory to monitor
WATCHED_DIR = "watched_folder"
LOG_FILE = "file_changes.log"

# Ensure the watched directory exists
os.makedirs(WATCHED_DIR, exist_ok=True)

class FileChangeHandler(FileSystemEventHandler):
    """Handles file changes and logs them."""

    def on_modified(self, event):
        """Triggered when a file is modified."""
        if not event.is_directory:
            log_change(f"Modified: {event.src_path}")

    def on_created(self, event):
        """Triggered when a file is created."""
        if not event.is_directory:
            log_change(f"Created: {event.src_path}")

    def on_deleted(self, event):
        """Triggered when a file is deleted."""
        if not event.is_directory:
            log_change(f"Deleted: {event.src_path}")

def log_change(message):
    """Logs the change to a file."""
    timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
    log_entry = f"{timestamp} - {message}\n"
    with open(LOG_FILE, "a") as log:
        log.write(log_entry)
    print(log_entry, end="")  # Print to console

def start_monitoring():
    """Starts the directory monitoring."""
    event_handler = FileChangeHandler()
    observer = Observer()
    observer.schedule(event_handler, WATCHED_DIR, recursive=False)
    observer.start()
    
    print(f"Monitoring '{WATCHED_DIR}' for changes... Press Ctrl+C to stop.")
    
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

# Start the file monitoring
start_monitoring()

How It Works:

  1. Watches a Directory (watched_folder) for file changes.
  2. Detects Events: When a file is created, modified, or deleted.
  3. Logs Changes:
    • Logs changes to a file (file_changes.log).
    • Displays changes in real-time on the console.

Expected Output (Console and Log File):

If a new file is created (test.txt)

2025-03-16 14:30:12 - Created: watched_folder/test.txt

If test.txt is modified

2025-03-16 14:31:00 - Modified: watched_folder/test.txt

If test.txt is deleted

2025-03-16 14:32:15 - Deleted: watched_folder/test.txt

Why Use This Approach?

Real-time monitoring of file changes
Automated logging for audits & tracking
Scalable (can be extended for subdirectories)
Useful for system admins, developers & security monitoring

This file-watching system can be extended to monitor log files, configuration files, or system directories for security and maintenance! 🚀