Skip to content

Commit c24c016

Browse files
committed
Fixed #211.
1 parent 4cbc5df commit c24c016

File tree

1 file changed

+34
-3
lines changed
  • addons/source-python/packages/source-python

1 file changed

+34
-3
lines changed

addons/source-python/packages/source-python/loggers.py

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,10 @@
1414
from logging import ERROR
1515
from logging import INFO
1616
from logging import WARNING
17-
from logging import FileHandler
1817
from logging import Formatter
1918
from logging import addLevelName
2019
from logging import getLogger
20+
from logging.handlers import TimedRotatingFileHandler
2121

2222
# Source.Python Imports
2323
# Core
@@ -258,6 +258,12 @@ def _log(self, level, msg, *args, **kwargs):
258258
# Print to the main SP log file?
259259
if SP_LOG & areas:
260260

261+
# Get the given extra dictionary
262+
extra = kwargs.setdefault('extra', dict())
263+
264+
# Set the logger name
265+
extra.setdefault('logger_name', self.logger.name)
266+
261267
# Print to the SP log file
262268
_sp_logger.logger.log(level, msg, *args, **kwargs)
263269

@@ -374,7 +380,8 @@ def __init__(
374380
log_path.parent.makedirs()
375381

376382
# Create the handler an add it to the logger
377-
self._handler = FileHandler(log_path, encoding=encoding)
383+
self._handler = DailyRotatingFileHandler(log_path, when='D',
384+
encoding=encoding)
378385
self._handler.setFormatter(self.formatter)
379386
self.logger.addHandler(self._handler)
380387

@@ -404,6 +411,30 @@ def _unload_instance(self):
404411
handler.close()
405412

406413

414+
class DailyRotatingFileHandler(TimedRotatingFileHandler):
415+
"""Source.Python's logging file handler."""
416+
417+
file_name_format = 'source-python.%Y-%m-%d.log'
418+
419+
def rotation_filename(self, default_name):
420+
"""Returns the name of today's log file."""
421+
return date.today().strftime(self.file_name_format)
422+
423+
def getFilesToDelete(self):
424+
"""Returns the files to delete."""
425+
files = list()
426+
for f in Path(self).parent.files():
427+
try:
428+
delta = date.today() - datetime.strptime(
429+
f.name, self.file_name_format).date()
430+
if delta.days < self.backupCount:
431+
continue
432+
files.append(f)
433+
except ValueError:
434+
continue
435+
return files
436+
437+
407438
# Set the core ConVars
408439
_level = ConVar(
409440
'sp_logging_level', '0', 'The Source.Python base logging level')
@@ -414,7 +445,7 @@ def _unload_instance(self):
414445
_sp_logger = LogManager(
415446
'sp', _level, _areas,
416447
'source-python.{0}'.format(date.today().strftime('%Y-%m-%d')),
417-
'%(asctime)s - %(name)s\t-\t%(levelname)s\t%(message)s',
448+
'%(asctime)s - %(logger_name)s\t-\t%(levelname)s\t%(message)s',
418449
'%Y-%m-%d %H:%M:%S')
419450

420451
# Set the parent logger level to allow all message types

0 commit comments

Comments
 (0)