Improved logging

This commit is contained in:
Daniel Dayley 2022-09-27 13:32:16 -06:00
parent 916f056844
commit f30d80b9b1
Signed by: Cronocide
GPG Key ID: 2CB7D4B8DEB3198E

View File

@ -72,6 +72,19 @@ import python-tool
##PLUGIN_ print("Unable to load plugin from " + filename + ": " + str(e)) ##PLUGIN_ print("Unable to load plugin from " + filename + ": " + str(e))
##PLUGIN_ return name_map ##PLUGIN_ return name_map
class LoggingFormatter(logging.Formatter):
def format(self, record):
module_max_width = 30
datefmt='%Y/%m/%d/ %H:%M:%S'
level = f'[{record.levelname}]'.ljust(9)
if 'log_module' not in dir(record) :
modname = str(record.module)+'.'+str(record.name)
else :
modname = record.log_module
modname = (f'{modname}'[:module_max_width-1] + ']').ljust(module_max_width)
final = "%-7s %s [%s %s" % (self.formatTime(record, self.datefmt), level, modname, record.getMessage())
return final
if __name__ == '__main__': if __name__ == '__main__':
# Command-line client # Command-line client
@ -85,15 +98,25 @@ if __name__ == '__main__':
parser.add_argument('-H', '--hosts', action='append', default=None, help='Collects arguments in an array.') parser.add_argument('-H', '--hosts', action='append', default=None, help='Collects arguments in an array.')
parser.add_argument('-d', '--dry-run', action='store_true', help='Store the existence of a variable.') parser.add_argument('-d', '--dry-run', action='store_true', help='Store the existence of a variable.')
parser.add_argument('-l', '--log', action='store', help='Specify a file to log to.') parser.add_argument('-l', '--log', action='store', help='Specify a file to log to.')
parser.add_argument('-v', '--debug', action='count', help='Include debug information in the output. Add \'v\'s for more output.',default=0) parser.add_argument('-v', '--verbose', action='count', help='Include verbose information in the output. Add \'v\'s for more output.',default=0)
args = parser.parse_args() args = parser.parse_args()
def debug(message,level) : log = logging.getLogger(__name__)
if args.debug >= level : log = logging.LoggerAdapter(log,{'log_module':'python-tool'})
print(message,file=sys.stderr)
# Configure logging
log_options = [logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG]
if not args.verbose :
args.verbose = 0
if args.verbose > 3 :
args.verbose = 3
if args.log : if args.log :
logging.basicConfig(level=logging.INFO,filename=args.log) logging.basicConfig(level=log_options[args.verbose],filename=args.log)
logging.getLogger().addHandler(logging.StreamHandler(sys.stderr))
else :
logging.basicConfig(level=log_options[args.verbose])
logging.getLogger().handlers[0].setFormatter(LoggingFormatter())
logging.propagate=True
##CONFIG_ # Parse config ##CONFIG_ # Parse config
##CONFIG_ try : ##CONFIG_ try :
@ -103,7 +126,7 @@ if __name__ == '__main__':
##CONFIG_ if not isinstance(config,dict) : ##CONFIG_ if not isinstance(config,dict) :
##CONFIG_ raise ValueError('expected dictonary as top-level yaml object') ##CONFIG_ raise ValueError('expected dictonary as top-level yaml object')
##CONFIG_ except Exception as e : ##CONFIG_ except Exception as e :
##CONFIG_ debug("Unable to parse config: " + str(e),0) ##CONFIG_ log.error("Unable to parse config: " + str(e),0)
##PLUGIN_ # Load plugins ##PLUGIN_ # Load plugins
##PLUGIN_ available_plugins = search_plugins(directory='/'.join(os.path.realpath(__file__).split('/')[:-2]) + '/python-tool/' + 'plugins') ##PLUGIN_ available_plugins = search_plugins(directory='/'.join(os.path.realpath(__file__).split('/')[:-2]) + '/python-tool/' + 'plugins')
##PLUGIN_ use_plugins([x for x in available_plugins.values()]) ##PLUGIN_ use_plugins([x for x in available_plugins.values()])