-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlog_file_cleaner.py
More file actions
64 lines (45 loc) · 1.88 KB
/
Copy pathlog_file_cleaner.py
File metadata and controls
64 lines (45 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import os # work with files and folders
import time # work with timestamps
from datetime import datetime, timedelta # easier date handling
# Folder containing your log files
log_folder = os.path.expanduser("~/Downloads") # change if needed
# Settings
days_to_keep = 7 # delete files older than this many days
max_file_size_mb = 5 # truncate files bigger than this size (in MB)
# Convert MB to bytes (because file sizes are in bytes)
max_file_size_bytes = max_file_size_mb * 1024 * 1024
# Get current time
now = time.time()
# Go through all files in the folder
for filename in os.listdir(log_folder):
file_path = os.path.join(log_folder, filename)
# Skip folders
if os.path.isdir(file_path):
continue
# Only process .log files (you can change this)
if not filename.endswith(".log"):
continue
# --- PART 1: Delete old files ---
# Get the last modified time of the file
file_modified_time = os.path.getmtime(file_path)
# Convert days_to_keep into seconds
age_limit = days_to_keep * 24 * 60 * 60
# If file is older than allowed → delete it
if now - file_modified_time > age_limit:
os.remove(file_path)
print(f"Deleted old log file: {filename}")
continue # skip to next file
# --- PART 2: Truncate large files ---
# Get file size in bytes
file_size = os.path.getsize(file_path)
if file_size > max_file_size_bytes:
print(f"Truncating large log file: {filename}")
# Read the last part of the file (keep recent logs)
with open(file_path, "r") as file:
lines = file.readlines()
# Keep only the last 100 lines (you can change this)
last_lines = lines[-100:]
# Write back only the last lines
with open(file_path, "w") as file:
file.writelines(last_lines)
print(f"Kept last 100 lines of {filename}")