improve logging and add randomgen and boolean
This commit is contained in:
parent
cf00c32a6b
commit
16397f8fc3
|
@ -4,9 +4,9 @@ from os import environ as env
|
|||
from datetime import datetime
|
||||
|
||||
|
||||
# Custom logger
|
||||
class Log():
|
||||
def __init__(self, minimum='INFO', datefmt='%Y-%m-%d %H:%M:%S', date=True):
|
||||
'''basic logging class'''
|
||||
def __init__(self, minimum='INFO', datefmt='%Y-%m-%d %H:%M:%S', date=True, systemd=True):
|
||||
self.levels = {
|
||||
'CRIT': 60,
|
||||
'ERROR': 50,
|
||||
|
@ -17,12 +17,13 @@ class Log():
|
|||
'MERP': 0
|
||||
}
|
||||
|
||||
self.systemd = True
|
||||
self.date = date
|
||||
self.datefmt = datefmt
|
||||
self.minimum = self._lvlCheck(minimum)
|
||||
|
||||
# make sure the minimum logging level is an int
|
||||
def _lvlCheck(self, level):
|
||||
'''make sure the minimum logging level is an int'''
|
||||
try:
|
||||
value = int(level)
|
||||
|
||||
|
@ -30,14 +31,36 @@ class Log():
|
|||
value = self.levels.get(level)
|
||||
|
||||
if value not in self.levels.values():
|
||||
raise InvalidLevel(f'Invalid logging level: {level}')
|
||||
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')
|
||||
|
||||
self.date = boolean
|
||||
|
||||
def setDate(self, datefmt):
|
||||
'''change the date format'''
|
||||
'''insert regex to make sure it is the correct format here'''
|
||||
self.datefmt = datefmt
|
||||
|
||||
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')
|
||||
|
||||
self.systemd = boolean
|
||||
|
||||
|
||||
def log(self, level, msg):
|
||||
'''log to the console'''
|
||||
levelNum = self._lvlCheck(level)
|
||||
|
||||
if type(level) == int:
|
||||
|
@ -50,8 +73,8 @@ class Log():
|
|||
|
||||
output = f'{level}: {msg}\n'
|
||||
|
||||
# Only show date when not running in systemd and date var is True
|
||||
if self.date and not env.get('INVOCATION_ID'):
|
||||
if self.date and (self.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)
|
||||
output = f'{date} {output}'
|
||||
|
||||
|
@ -59,7 +82,6 @@ class Log():
|
|||
stdout.write(output)
|
||||
stdout.flush()
|
||||
|
||||
|
||||
def critical(self, msg):
|
||||
self.log('CRIT', msg)
|
||||
|
||||
|
@ -82,8 +104,42 @@ class Log():
|
|||
self.log('MERP', msg)
|
||||
|
||||
|
||||
class InvalidType(Exception):
|
||||
'''Raise when the log level isn't a str or an int'''
|
||||
def getLogger(loginst):
|
||||
'''get a logging instance'''
|
||||
Logger = logger.get(loginst)
|
||||
|
||||
if not Logger:
|
||||
raise
|
||||
|
||||
|
||||
'''create a default logger'''
|
||||
logger = {
|
||||
'default': Log()
|
||||
}
|
||||
|
||||
DefaultLog = logger['default']
|
||||
|
||||
|
||||
'''aliases for default logger's log output functions'''
|
||||
critical = DefaultLog.critical
|
||||
error = DefaultLog.error
|
||||
warning = DefaultLog.error
|
||||
info = DefaultLog.info
|
||||
verbose = DefaultLog.verbose
|
||||
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'''
|
||||
|
|
|
@ -1,5 +1,38 @@
|
|||
from .logging import Log
|
||||
import random, string
|
||||
|
||||
from . import logging
|
||||
|
||||
|
||||
def boolean(v, fail=True):
|
||||
if type(v) in [dict, list, tuple]:
|
||||
raise ValueError(f'Value is not a string, boolean, int, or nonetype: {value}')
|
||||
|
||||
'''make the value lowercase if it's a string'''
|
||||
value = v.lower() if type(value) == str else v
|
||||
|
||||
if value in [1, True, 'on', 'y', 'yes', 'true', 'enable']:
|
||||
'''convert string to True'''
|
||||
return True
|
||||
|
||||
elif value in [0, False, None, 'off', 'n', 'no', 'false', 'disable', '']:
|
||||
'''convert string to False'''
|
||||
return False
|
||||
|
||||
elif not fail:
|
||||
'''just return the value'''
|
||||
return value
|
||||
|
||||
else:
|
||||
raise ValueError(f'Value cannot be converted to a boolean: {value}')
|
||||
|
||||
|
||||
def randomgen(chars=20):
|
||||
if type(chars) != int:
|
||||
raise TypeError(f'Character length must be an integer, not a {type(char)}')
|
||||
|
||||
return ''.join(random.choices(string.ascii_letters + string.digits, k=chars))
|
||||
|
||||
|
||||
def merp():
|
||||
Log('MERP', date=False).merp('heck')
|
||||
logging.setLevel('MERP')
|
||||
logging.merp('heck')
|
||||
|
|
Loading…
Reference in a new issue