Skip to content

Commit 242ccd8

Browse files
authored
Merge pull request sumanth-0#797 from akashadsare/add-auto-log-file-archiver
Add Auto Log File Archiver - Issue sumanth-0#787
2 parents dbae325 + a4e2cdd commit 242ccd8

File tree

2 files changed

+195
-0
lines changed

2 files changed

+195
-0
lines changed

Auto_Log_File_Archiver/README.md

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# Auto Log File Archiver
2+
3+
A minimal Python script that automatically moves log files older than a week to an "archive" folder.
4+
5+
## Features
6+
7+
- **Automatic Detection**: Finds log files (`.log`, `.txt`, `.out`)
8+
- **Age Check**: Identifies files older than 7 days
9+
- **Archive Creation**: Creates archive folder automatically
10+
- **Duplicate Handling**: Adds timestamps to prevent overwrites
11+
- **Sample Generation**: Creates test logs for demonstration
12+
13+
## Usage
14+
15+
### Interactive Mode
16+
```bash
17+
python log_archiver.py
18+
```
19+
20+
### With Custom Directories
21+
```bash
22+
# Will prompt for directories
23+
python log_archiver.py
24+
```
25+
26+
## File Types Archived
27+
28+
- `.log` files
29+
- `.txt` files
30+
- `.out` files
31+
32+
## Example Output
33+
34+
```
35+
Auto Log File Archiver
36+
=========================
37+
Enter log directory (or press Enter for sample):
38+
Created sample logs in: sample_logs
39+
40+
Enter archive directory (optional):
41+
42+
Scanning: sample_logs
43+
Archived: old.log
44+
45+
Archived 1 log file(s)
46+
```
47+
48+
## How It Works
49+
50+
1. **Scan Directory**: Looks for log files in specified directory
51+
2. **Check Age**: Uses file modification time to determine age
52+
3. **Create Archive**: Makes "archive" subfolder if needed
53+
4. **Move Files**: Moves files older than 7 days to archive
54+
5. **Handle Duplicates**: Adds timestamp suffix if file exists
55+
56+
## Sample Test
57+
58+
The script can create sample logs for testing:
59+
- `recent.log` - Current timestamp (not archived)
60+
- `old.log` - 10 days old (gets archived)
61+
62+
## Requirements
63+
64+
- Python 3.6+
65+
- No external dependencies
66+
67+
## Error Handling
68+
69+
- Permission errors are caught and reported
70+
- Missing directories show appropriate messages
71+
- File operation errors are handled gracefully
72+
73+
## Author
74+
75+
Created for issue #787 - 100 Lines of Python Code Project
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
#!/usr/bin/env python3
2+
import os
3+
import shutil
4+
import time
5+
from datetime import datetime, timedelta
6+
7+
8+
def get_log_files(directory):
9+
"""Get all log files from directory."""
10+
log_extensions = ['.log', '.txt', '.out']
11+
log_files = []
12+
13+
try:
14+
for file in os.listdir(directory):
15+
if any(file.lower().endswith(ext) for ext in log_extensions):
16+
log_files.append(os.path.join(directory, file))
17+
except PermissionError:
18+
print(f"Permission denied: {directory}")
19+
except FileNotFoundError:
20+
print(f"Directory not found: {directory}")
21+
22+
return log_files
23+
24+
25+
def is_older_than_week(file_path):
26+
"""Check if file is older than a week."""
27+
try:
28+
file_time = os.path.getmtime(file_path)
29+
file_date = datetime.fromtimestamp(file_time)
30+
week_ago = datetime.now() - timedelta(days=7)
31+
return file_date < week_ago
32+
except OSError:
33+
return False
34+
35+
36+
def archive_logs(log_dir, archive_dir=None):
37+
"""Archive log files older than a week."""
38+
if not archive_dir:
39+
archive_dir = os.path.join(log_dir, "archive")
40+
41+
# Create archive directory if it doesn't exist
42+
os.makedirs(archive_dir, exist_ok=True)
43+
44+
log_files = get_log_files(log_dir)
45+
archived_count = 0
46+
47+
for log_file in log_files:
48+
if is_older_than_week(log_file):
49+
try:
50+
filename = os.path.basename(log_file)
51+
archive_path = os.path.join(archive_dir, filename)
52+
53+
# Handle duplicate names by adding timestamp
54+
if os.path.exists(archive_path):
55+
name, ext = os.path.splitext(filename)
56+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
57+
filename = f"{name}_{timestamp}{ext}"
58+
archive_path = os.path.join(archive_dir, filename)
59+
60+
shutil.move(log_file, archive_path)
61+
print(f"Archived: {filename}")
62+
archived_count += 1
63+
64+
except Exception as e:
65+
print(f"Error archiving {log_file}: {e}")
66+
67+
return archived_count
68+
69+
70+
def create_sample_logs(directory):
71+
"""Create sample log files for testing."""
72+
os.makedirs(directory, exist_ok=True)
73+
74+
# Create recent log
75+
recent_log = os.path.join(directory, "recent.log")
76+
with open(recent_log, 'w') as f:
77+
f.write("Recent log entry\n")
78+
79+
# Create old log (simulate 10 days old)
80+
old_log = os.path.join(directory, "old.log")
81+
with open(old_log, 'w') as f:
82+
f.write("Old log entry\n")
83+
84+
# Set old file timestamp to 10 days ago
85+
ten_days_ago = time.time() - (10 * 24 * 60 * 60)
86+
os.utime(old_log, (ten_days_ago, ten_days_ago))
87+
88+
print(f"Created sample logs in: {directory}")
89+
90+
91+
def main():
92+
"""Main function."""
93+
print("Auto Log File Archiver")
94+
print("=" * 25)
95+
96+
log_dir = input("Enter log directory (or press Enter for sample): ").strip()
97+
98+
if not log_dir:
99+
log_dir = "sample_logs"
100+
create_sample_logs(log_dir)
101+
102+
if not os.path.exists(log_dir):
103+
print(f"Directory not found: {log_dir}")
104+
return
105+
106+
archive_dir = input("Enter archive directory (optional): ").strip()
107+
if not archive_dir:
108+
archive_dir = None
109+
110+
print(f"\nScanning: {log_dir}")
111+
archived_count = archive_logs(log_dir, archive_dir)
112+
113+
if archived_count > 0:
114+
print(f"\nArchived {archived_count} log file(s)")
115+
else:
116+
print("\nNo log files to archive")
117+
118+
119+
if __name__ == "__main__":
120+
main()

0 commit comments

Comments
 (0)