-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathLog.py
More file actions
174 lines (147 loc) · 5.21 KB
/
Log.py
File metadata and controls
174 lines (147 loc) · 5.21 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import os
import logging
from logging.handlers import RotatingFileHandler
class LogHandler:
"""
A class to manage and configure a rotating logger.
Features:
- Configurable base directory for logs.
- Automatic rotation by file size using RotatingFileHandler.
- Easy methods to clear the log file or rotate logs on demand.
- Ability to set the logging level dynamically.
- Convenience methods for adding log lines at various severity levels.
- Safe initialization to prevent multiple handlers being attached.
"""
def __init__(
self,
logger_name: str = "my_logger",
log_filename: str = "debug.log",
backup_filename: str = "debug.log.old", # For demonstration if you want manual rename.
base_dir: str = ".",
max_bytes: int = 1_000_000, # 1 MB
backup_count: int = 1
):
"""
:param logger_name: Name of the logger.
:param log_filename: Primary log file name.
:param backup_filename: Name for backup logs (optional; if you want to rename manually).
:param base_dir: Base directory where log files should be stored.
:param max_bytes: Max file size (in bytes) before rotating.
:param backup_count: Number of backup files to keep.
"""
self.logger_name: str = logger_name
self.log_filename: str = log_filename
self.backup_filename: str = backup_filename
self.base_dir: str = base_dir
self.max_bytes: int = max_bytes
self.backup_count: int = backup_count
self.level = logging.DEBUG
# Internal references
self._logger = None
self._log_path = os.path.join(self.base_dir, self.log_filename)
self._setup_logger()
def _setup_logger(self):
"""
Sets up the logger if it hasn't been created yet.
"""
# Create directories if they don't exist
os.makedirs(self.base_dir, exist_ok=True)
self._logger = logging.getLogger(self.logger_name)
self._logger.setLevel(self.level)
# Prevent attaching multiple handlers if re-initialized
if not self._logger.handlers:
rotating_handler = RotatingFileHandler(
filename=self._log_path,
mode="a+",
encoding="utf-8",
maxBytes=self.max_bytes,
backupCount=self.backup_count,
)
formatter = logging.Formatter(
fmt="%(asctime)s [%(levelname)-8s] %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
rotating_handler.setFormatter(formatter)
self._logger.addHandler(rotating_handler)
self.rotate_if_needed()
# -----------------------
# Getter & utility methods
# -----------------------
def get_logger(self) -> logging.Logger:
"""
Return the underlying logger instance.
"""
return self._logger
def get_log_path(self) -> str:
"""
Returns the full path of the log file.
"""
return self._log_path
def set_level(self, level: int):
"""
Dynamically set the logging level.
:param level: Logging level (e.g., logging.DEBUG, logging.INFO).
"""
self._logger.setLevel(level)
def clear_log(self):
"""
Clears the contents of the current log file.
"""
with open(self._log_path, "w"):
pass
def logfile_exists(self) -> bool:
"""
Check if the log file exists and filesize > 0
"""
if os.path.exists(self._log_path):
return os.path.getsize(self._log_path) > 0
return False
def rotate_logs(self):
"""
Manually force the rotation of logs, if you ever need that.
"""
for handler in self._logger.handlers:
if isinstance(handler, RotatingFileHandler):
handler.doRollover()
def rotate_if_needed(self):
"""
Rotate logs if the current log file exceeds the max size.
"""
for handler in self._logger.handlers:
if isinstance(handler, RotatingFileHandler):
if os.path.exists(self._log_path):
if os.path.getsize(self._log_path) > self.max_bytes:
handler.doRollover()
# -----------------------
# Convenience log methods
# -----------------------
def debug(self, msg: str):
"""
Add a debug-level log message.
"""
self._logger.debug(msg)
def info(self, msg: str):
"""
Add an info-level log message.
"""
self._logger.info(msg)
def warning(self, msg: str):
"""
Add a warning-level log message.
"""
self._logger.warning(msg)
def error(self, msg: str):
"""
Add an error-level log message.
"""
self._logger.error(msg)
def critical(self, msg: str):
"""
Add a critical-level log message.
"""
self._logger.critical(msg)
def log(self, level: int, msg: str):
"""
Add a log message at a specified level.
"""
self._logger.log(level, msg)