From acf72f06c2c4c1bbcd109f53940c12ae70d25505 Mon Sep 17 00:00:00 2001 From: Izalia Mae Date: Sat, 7 Mar 2020 03:02:30 -0500 Subject: [PATCH] improve logging config --- IzzyLib/logging.py | 110 +++++++++++++++++++++++++++------------------ IzzyLib/misc.py | 4 +- 2 files changed, 68 insertions(+), 46 deletions(-) diff --git a/IzzyLib/logging.py b/IzzyLib/logging.py index 200cfcc..cc91e9f 100644 --- a/IzzyLib/logging.py +++ b/IzzyLib/logging.py @@ -9,9 +9,15 @@ from os import environ as env from datetime import datetime +stdout = sys.stdout + + class Log(): - '''basic logging class''' - def __init__(self, minimum='INFO', datefmt='%Y-%m-%d %H:%M:%S', date=True, systemd=True): + def __init__(self, config=dict()): + '''setup the logger''' + if not isinstance(config, dict): + raise TypeError(f'config is not a dict') + self.levels = { 'CRIT': 60, 'ERROR': 50, @@ -22,10 +28,9 @@ class Log(): 'MERP': 0 } - self.systemd = True - self.date = date - self.datefmt = datefmt - self.minimum = self._lvlCheck(minimum) + self.config = dict() + self.setConfig(config) + def _lvlCheck(self, level): '''make sure the minimum logging level is an int''' @@ -33,36 +38,48 @@ class Log(): value = int(level) except ValueError: - value = self.levels.get(level) + value = self.levels.get(level.upper()) if value not in self.levels.values(): raise error.InvalidLevel(f'Invalid logging level: {level}') return value - def setLevel(self, level): - '''change the minimum logging level''' - self.minimum = self._lvlCheck(level) - def setDateEnable(self, boolean): - '''enable or disable printing the date''' - if type(boolean) != bool: - raise TypeError(f'{boolean} is not a boolean') + def _parseConfig(self, config): + '''parse the new config and update the old values''' + date = config.get('date', self.config.get('date',True)) + systemd = config.get('systemd', self.config.get('systemd,', True)) - self.date = boolean + if not isinstance(date, bool): + raise TypeError(f'value for "date" is not a boolean: {date}') - def setDate(self, datefmt): - '''change the date format''' - '''insert regex to make sure it is the correct format here''' - self.datefmt = datefmt + if not isinstance(systemd, bool): + raise TypeError(f'value for "systemd" is not a boolean: {date}') - def setSystemd(self, boolean): - '''enable or disable checking if the script is running in systemd''' - if type(boolean) != bool: - raise TypeError(f'{boolean} is not a boolean') + return { + 'level': self._lvlCheck(config.get('level', self.config.get('level', 'INFO'))), + 'datefmt': config.get('datefmt', self.config.get('datefmt', '%Y-%m-%d %H:%M:%S')), + 'date': date, + 'systemd': systemd + } - self.systemd = boolean + def setConfig(self, config): + '''set the config''' + self.config = self._parseConfig(config) + + + def getConfig(self): + '''return the current config''' + return self.config + + + def printConfig(self): + for k,v in self.config.items(): + stdout.write(f'{k}: {v}\n') + + stdout.flush() def log(self, level, msg): '''log to the console''' @@ -73,20 +90,20 @@ class Log(): if v == levelNum: level = k - if levelNum < self.minimum: + if levelNum < self.config['level']: return output = f'{level}: {msg}\n' - if self.date and (self.systemd and not env.get('INVOCATION_ID')): + if self.config['date'] and (self.config['systemd'] and not env.get('INVOCATION_ID')): '''only show date when not running in systemd and date var is True''' - date = datetime.now().strftime(self.datefmt) + date = datetime.now().strftime(self.config['datefmt']) output = f'{date} {output}' - stdout = sys.stdout stdout.write(output) stdout.flush() + def critical(self, msg): self.log('CRIT', msg) @@ -109,12 +126,27 @@ class Log(): self.log('MERP', msg) -def getLogger(loginst): - '''get a logging instance''' +def getLogger(loginst, config=None): + '''get a logging instance and create one if it doesn't exist''' Logger = logger.get(loginst) if not Logger: - raise + if config: + logger[loginst] = Log(config) + + else: + raise error.InvalidLogger(f'logger "{loginst}" doesn\'t exist') + + return logger[loginst] + +class error: + '''base class for all errors''' + + class InvalidLevel(Exception): + '''Raise when an invalid logging level was specified''' + + class InvalidLogger(Exception): + '''Raise when the specified logger doesn't exist''' '''create a default logger''' @@ -135,16 +167,6 @@ debug = DefaultLog.debug merp = DefaultLog.merp '''aliases for the default logger's config functions''' -'''will probably change this to setConfig to simplify things''' -setLevel = DefaultLog.setLevel -setDateEnable = DefaultLog.setDateEnable -setDate = DefaultLog.setDate -setSystemd = DefaultLog.setSystemd - - -class error: - class InvalidLevel(Exception): - '''Raise when an invalid logging level was specified''' - - class InvalidLogger(Exception): - '''Raise when the specified logger doesn't exist''' +setConfig = DefaultLog.setConfig +getConfig = DefaultLog.getConfig +printConfig = DefaultLog.printConfig diff --git a/IzzyLib/misc.py b/IzzyLib/misc.py index 6940241..7fe92bc 100644 --- a/IzzyLib/misc.py +++ b/IzzyLib/misc.py @@ -45,5 +45,5 @@ def formatUTC(timestamp=None): def merp(): - logging.setLevel('MERP') - logging.merp('heck') + log = logging.getLogger('merp-heck', {'level': 'merp', 'date': False}) + log.merp('heck')