improve logging config

This commit is contained in:
Izalia Mae 2020-03-07 03:02:30 -05:00
parent 95d5da969a
commit acf72f06c2
2 changed files with 68 additions and 46 deletions

View file

@ -9,9 +9,15 @@ from os import environ as env
from datetime import datetime from datetime import datetime
stdout = sys.stdout
class Log(): class Log():
'''basic logging class''' def __init__(self, config=dict()):
def __init__(self, minimum='INFO', datefmt='%Y-%m-%d %H:%M:%S', date=True, systemd=True): '''setup the logger'''
if not isinstance(config, dict):
raise TypeError(f'config is not a dict')
self.levels = { self.levels = {
'CRIT': 60, 'CRIT': 60,
'ERROR': 50, 'ERROR': 50,
@ -22,10 +28,9 @@ class Log():
'MERP': 0 'MERP': 0
} }
self.systemd = True self.config = dict()
self.date = date self.setConfig(config)
self.datefmt = datefmt
self.minimum = self._lvlCheck(minimum)
def _lvlCheck(self, level): def _lvlCheck(self, level):
'''make sure the minimum logging level is an int''' '''make sure the minimum logging level is an int'''
@ -33,36 +38,48 @@ class Log():
value = int(level) value = int(level)
except ValueError: except ValueError:
value = self.levels.get(level) value = self.levels.get(level.upper())
if value not in self.levels.values(): if value not in self.levels.values():
raise error.InvalidLevel(f'Invalid logging level: {level}') raise error.InvalidLevel(f'Invalid logging level: {level}')
return value return value
def setLevel(self, level):
'''change the minimum logging level'''
self.minimum = self._lvlCheck(level)
def setDateEnable(self, boolean): def _parseConfig(self, config):
'''enable or disable printing the date''' '''parse the new config and update the old values'''
if type(boolean) != bool: date = config.get('date', self.config.get('date',True))
raise TypeError(f'{boolean} is not a boolean') 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): if not isinstance(systemd, bool):
'''change the date format''' raise TypeError(f'value for "systemd" is not a boolean: {date}')
'''insert regex to make sure it is the correct format here'''
self.datefmt = datefmt
def setSystemd(self, boolean): return {
'''enable or disable checking if the script is running in systemd''' 'level': self._lvlCheck(config.get('level', self.config.get('level', 'INFO'))),
if type(boolean) != bool: 'datefmt': config.get('datefmt', self.config.get('datefmt', '%Y-%m-%d %H:%M:%S')),
raise TypeError(f'{boolean} is not a boolean') '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): def log(self, level, msg):
'''log to the console''' '''log to the console'''
@ -73,20 +90,20 @@ class Log():
if v == levelNum: if v == levelNum:
level = k level = k
if levelNum < self.minimum: if levelNum < self.config['level']:
return return
output = f'{level}: {msg}\n' 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''' '''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}' output = f'{date} {output}'
stdout = sys.stdout
stdout.write(output) stdout.write(output)
stdout.flush() stdout.flush()
def critical(self, msg): def critical(self, msg):
self.log('CRIT', msg) self.log('CRIT', msg)
@ -109,12 +126,27 @@ class Log():
self.log('MERP', msg) self.log('MERP', msg)
def getLogger(loginst): def getLogger(loginst, config=None):
'''get a logging instance''' '''get a logging instance and create one if it doesn't exist'''
Logger = logger.get(loginst) Logger = logger.get(loginst)
if not Logger: 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''' '''create a default logger'''
@ -135,16 +167,6 @@ debug = DefaultLog.debug
merp = DefaultLog.merp merp = DefaultLog.merp
'''aliases for the default logger's config functions''' '''aliases for the default logger's config functions'''
'''will probably change this to setConfig to simplify things''' setConfig = DefaultLog.setConfig
setLevel = DefaultLog.setLevel getConfig = DefaultLog.getConfig
setDateEnable = DefaultLog.setDateEnable printConfig = DefaultLog.printConfig
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'''

View file

@ -45,5 +45,5 @@ def formatUTC(timestamp=None):
def merp(): def merp():
logging.setLevel('MERP') log = logging.getLogger('merp-heck', {'level': 'merp', 'date': False})
logging.merp('heck') log.merp('heck')