/
loggers.py
405 lines (314 loc) · 11.4 KB
/
loggers.py
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
# ../loggers.py
"""Provides logging functionality."""
# =============================================================================
# >> IMPORTS
# =============================================================================
# Python Imports
# Datetime
from datetime import date
# Logging
from logging import CRITICAL
from logging import DEBUG
from logging import ERROR
from logging import INFO
from logging import WARNING
from logging import FileHandler
from logging import Formatter
from logging import addLevelName
from logging import getLogger
# Source.Python Imports
# Cvars
from cvars import ConVar
# Paths
from paths import LOG_PATH
# =============================================================================
# >> ALL DECLARATION
# =============================================================================
__all__ = ('LogManager',
'_LogInstance',
)
# =============================================================================
# >> GLOBAL VARIABLES
# =============================================================================
# Store the areas constants
CONSOLE = 1 << 0
MAIN_LOG = 1 << 1
SP_LOG = 1 << 2
SCRIPT_LOG = 1 << 3
# Store the new level names
MESSAGE = 60
EXCEPTION = ERROR
# Add the new level names
addLevelName(MESSAGE, 'MESSAGE')
addLevelName(EXCEPTION, 'EXCEPTION')
# Store a formatter for use with the main log
_main_log_formatter = Formatter('- %(name)s\t-\t%(levelname)s\n\t%(message)s')
# =============================================================================
# >> CLASSES
# =============================================================================
class _LogInstance(dict):
"""Base logging class used to create child logging instances."""
def __init__(self, parent=None, name=None):
"""Store the parent and gets a child of the parent.
:param _LogInstance parent:
A parent logger or None.
:param str name:
A name for the logger or None.
"""
# Initialize the dictionary
super().__init__()
# Store the parent instance
self.parent = parent
# Was a parent class passed?
if self.parent is not None:
# Store a child logging instance
self._logger = self.parent.logger.getChild(name)
def __missing__(self, item):
"""Add new items as logging instances.
:rtype: _LogInstance
"""
# Get the new logging instance
value = self[item] = _LogInstance(self, item)
# Return the logging instance
return value
def __getattr__(self, attr):
"""Return the logger with the specified name.
:rtype: _LogInstance
"""
return self[attr]
def __delitem__(self, item):
"""Remove all children of the instance and closes the logger."""
# Remove all children
self[item].clear()
# Close the logger
self.logger.close()
def clear(self):
"""Delete each item individually to close all loggers."""
# Loop through each child
for item in list(self):
# Remove the child
del self[item]
def log_critical(self, msg, *args, **kwargs):
"""Use to call a critical message.
:param str msg:
Message to log.
:param args:
Additional arguments that are used for formatting purpose.
:param kwargs:
Additional keywords that are used for formatting purpose.
"""
self._log(CRITICAL, msg, *args, **kwargs)
def log_debug(self, msg, *args, **kwargs):
"""Use to call a debug message.
:param str msg:
Message to log.
:param args:
Additional arguments that are used for formatting purpose.
:param kwargs:
Additional keywords that are used for formatting purpose.
"""
self._log(DEBUG, msg, *args, **kwargs)
def log_exception(self, msg, *args, **kwargs):
"""Use to call an exception message.
:param str msg:
Message to log.
:param args:
Additional arguments that are used for formatting purpose.
:param kwargs:
Additional keywords that are used for formatting purpose.
"""
self._log(EXCEPTION, msg, *args, **kwargs)
def log_info(self, msg, *args, **kwargs):
"""Use to call a basic info message.
:param str msg:
Message to log.
:param args:
Additional arguments that are used for formatting purpose.
:param kwargs:
Additional keywords that are used for formatting purpose.
"""
self._log(INFO, msg, *args, **kwargs)
def log_warning(self, msg, *args, **kwargs):
"""Use to call a warning message.
:param str msg:
Message to log.
:param args:
Additional arguments that are used for formatting purpose.
:param kwargs:
Additional keywords that are used for formatting purpose.
"""
self._log(WARNING, msg, *args, **kwargs)
def log_message(self, msg, *args, **kwargs):
"""Use to call a message that should always print.
:param str msg:
Message to log.
:param args:
Additional arguments that are used for formatting purpose.
:param kwargs:
Additional keywords that are used for formatting purpose.
"""
self._log(MESSAGE, msg, *args, **kwargs)
def log(self, level, msg, *args, **kwargs):
"""Use to call a message with the given logging level.
:param int level:
Level of the message to log.
:param str msg:
Message to log.
:param args:
Additional arguments that are used for formatting purpose.
:param kwargs:
Additional keywords that are used for formatting purpose.
"""
# Get the value of the given level
level = self._get_level_value(level)
# Call the main logging method
self._log(level, msg, *args, **kwargs)
def _log(self, level, msg, *args, **kwargs):
"""Main logging method."""
# Does the message need logged?
if self.level > level:
# If not, simply return
return
# Get the areas to be used
areas = self.areas
# Print to main log file?
if MAIN_LOG & areas:
# Import engine_server
# This is done here to fix an ImportError
from engines.server import engine_server
# Create the record
record = self.logger.makeRecord(
self.logger.name, level,
'(unknown file)', 0, msg, args, None)
# Get the message to send
message = _main_log_formatter.format(record)
# Print to the main log
engine_server.log_print(message + '\n')
# Print to the console?
if CONSOLE & areas:
# If not, print to the console
# If <engine>.log_print is called with logging being on,
# the console is already echoed with the message.
from core import echo_console
echo_console(msg)
# Print to the script's log file?
if SCRIPT_LOG & areas and self.root != _sp_logger:
# Print message to the log file
self.logger.log(level, msg, *args, **kwargs)
# Print to the main SP log file?
if SP_LOG & areas:
# Print to the SP log file
_sp_logger.logger.log(level, msg, *args, **kwargs)
@staticmethod
def _get_level_value(level):
"""Return a level value used by the logging package.
:rtype: int
"""
return 50 - (10 * level)
@property
def root(self):
"""Return the root logger.
:rtype: _LogInstance
"""
# Store the current instance
instance = self
# Use a while statement to get the parent until root is found
while instance.parent is not None:
# Set the current instance to the parent
instance = instance.parent
# Return the root instance
return instance
@property
def areas(self):
"""Return the root's areas value.
:rtype: int
"""
return self.root.areas
@property
def level(self):
"""Return the root's level value.
:rtype: int
"""
return self.root.level
@property
def formatter(self):
"""Return the root's formatter.
:rtype: Formatter
"""
return self.root._formatter
@property
def logger(self):
"""Return the instance's logger.
:rtype: logging.Logger
"""
return self._logger
class LogManager(_LogInstance):
"""Main log class used as a root to create children instances."""
def __init__(
self, name, level, areas, filepath=None,
log_format=None, date_format=None):
"""Store the base values and creates the logger.
:param str name:
Name of the base logger.
:param ConVar level:
A console variable that defines required level to log a message.
:param ConVar areas:
A console variable that defines the areas where messages are
getting logged.
:param str filepath:
A file where messages are getting logged.
:param str log_format:
A custom log format that defines the appearance of the messages.
:param str date_format:
A custom date format that defines how the date is printed.
"""
# Initialize the dictionary
super().__init__()
# Store the base formatter
self._formatter = Formatter(log_format, date_format)
# Store the base attributes
self._level = level
self._areas = areas
# Create the logger
self._logger = getLogger(name)
# Was a filepath given?
if filepath is not None:
# Does the given path end with the extension?
if filepath.endswith('.log'):
# Remove the extension
filepath = filepath[:~3]
# Get the path to the log file
log_path = LOG_PATH / filepath + '.log'
# Does the parent directory exist?
if not log_path.parent.isdir():
# Create the parent directory
log_path.parent.makedirs()
# Create the handler an add it to the logger
self._handler = FileHandler(log_path)
self._handler.setFormatter(self.formatter)
self.logger.addHandler(self._handler)
@property
def level(self):
"""Return the needed level value.
:rtype: int
"""
return 50 - (self._level.get_int() * 10)
@property
def areas(self):
"""Return the areas to print messages to.
:rtype: int
"""
return self._areas.get_int()
# Set the core ConVars
_level = ConVar(
'sp_logging_level', '0', 'The Source.Python base logging level')
_areas = ConVar(
'sp_logging_areas', '1', 'The Source.Python base logging areas')
# Get the Source.Python main LogManager instance
_sp_logger = LogManager(
'sp', _level, _areas,
'source-python.{0}'.format(date.today().strftime('%Y-%m-%d')),
'%(asctime)s - %(name)s\t-\t%(levelname)s\t%(message)s',
'%Y-%m-%d %H:%M:%S')
# Set the parent logger level to allow all message types
_sp_logger.logger.parent.level = DEBUG