Created
March 12, 2025 15:21
-
-
Save sam2332/f88f5b75ea2f6c4f60cad9e458b66d98 to your computer and use it in GitHub Desktop.
log all file events to a sqllite file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import logging | |
from watchdog.observers import Observer | |
from watchdog.events import FileSystemEventHandler | |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') | |
logger = logging.getLogger(__name__) | |
file_handler = logging.FileHandler('filehawk.log') | |
file_handler.setLevel(logging.INFO) | |
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') | |
file_handler.setFormatter(formatter) | |
#logger.addHandler(file_handler) | |
##log to databse | |
import sqlite3 | |
conn = sqlite3.connect('filehawk.db') | |
c = conn.cursor() | |
c.execute('''CREATE TABLE IF NOT EXISTS filehawk (id INTEGER PRIMARY KEY AUTOINCREMENT, action TEXT, file TEXT, timestamp TEXT)''') | |
conn.commit() | |
# Event Handler class to watch for changes | |
class LogAllhangeHandler(FileSystemEventHandler): | |
def on_deleted(self, event): | |
with conn.cursor() as c: | |
c.execute("INSERT INTO filehawk (action, file, timestamp) VALUES (?, ?, datetime('now'))", ('deleted', event.src_path)) | |
conn.commit() | |
logger.info(f"Deleted: {event.src_path}") | |
def on_modified(self, event): | |
with conn.cursor() as c: | |
c.execute("INSERT INTO filehawk (action, file, timestamp) VALUES (?, ?, datetime('now'))", ('modified', event.src_path)) | |
conn.commit() | |
logger.info(f"Modified: {event.src_path}") | |
def on_created(self, event): | |
with conn.cursor() as c: | |
c.execute("INSERT INTO filehawk (action, file, timestamp) VALUES (?, ?, datetime('now'))", ('created', event.src_path)) | |
conn.commit() | |
logger.info(f"Created: {event.src_path}") | |
local_path = os.path.expanduser('.') | |
# Set up the observer to watch the local directory | |
logger.info(f"Starting to watch for changes in: {local_path}") | |
event_handler = LogAllhangeHandler() | |
observer = Observer() | |
observer.schedule(event_handler, local_path, recursive=True) | |
observer.start() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment