-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogger.py
More file actions
70 lines (57 loc) · 2.17 KB
/
logger.py
File metadata and controls
70 lines (57 loc) · 2.17 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
65
66
67
68
69
70
#logger.py
"""
Simple logger for debugging or saving system behavior.
"""
from datetime import datetime
import threading
ALLOWED_LEVELS = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
DEBUG = "DEBUG"
INFO = "INFO"
WARNING = "WARNING"
ERROR = "ERROR"
CRIT = "CRITICAL"
class Logger:
def __init__(self, log_to_file=False, filename="log.txt", verbose=True):
self.logs = []
self.log_to_file = log_to_file
self.filename = filename
self.verbose = verbose
self.lock = threading.Lock()
if log_to_file:
with open(filename, 'a') as f:
f.write(f"=== Logger Started at {datetime.now().isoformat()} ===\n")
def log(self, msg, level="INFO"):
if level.upper() not in ALLOWED_LEVELS:
level = ALLOWED_LEVELS[1]
timestamp = datetime.now().isoformat()
entry = f"[{timestamp}] [{level.upper()}] {msg}"
with self.lock:
self.logs.append(entry)
if self.verbose:
print(entry)
if self.log_to_file:
with open(self.filename, 'a') as f:
f.write(f"{entry}\n")
def get_logs(self, level=None):
with self.lock:
if not level:
return self.logs.copy()
level = level.upper()
if level not in ALLOWED_LEVELS:
return []
return [log for log in self.logs if f"[{level}]" in log]
def clear_logs(self):
with self.lock:
self.logs.clear()
if self.log_to_file:
with open(self.filename, 'w') as f:
f.write("=== Logs Cleared ===\n")
def log_function_start(self, name):
self.log(f"Staring function: {name}", DEBUG)
def log_function_end(self, name, return_value, success=True):
self.log(f"Exiting function: {name} - Success [{success}] - Returning {return_value}", DEBUG)
def log_phase_begin(self, phases, phase_num):
self.log(f"Starting Phase {phase_num+1}: {phases[phase_num]}", DEBUG)
def advance_phase(self, phases, phase_num):
self.log_phase_begin(phases, phase_num)
return phase_num + 1