#!/usr/bin/env python#-*-coding:utf-8-*-" "the log class can output different levels of logs to different log files" "ImportOSImportSYSImport TimeImportLoggingImportinspecthandlers= {logging. NOTSET:"/tmp/tnlog-notset.log", logging. DEBUG:"/tmp/tnlog-debug.log", Logging.info:"/tmp/tnlog-info.log", logging. WARNING:"/tmp/tnlog-warning.log", logging. ERROR:"/tmp/tnlog-error.log", logging. CRITICAL:"/tmp/tnlog-critical.log"}defcreatehandlers (): Loglevels=Handlers.keys () forLevelinchLoglevels:path=Os.path.abspath (Handlers[level]) Handlers[level]=logging. Filehandler (PATH)#Create global variables when loading modulescreatehandlers ()classTnlog (object):defPrintfnow (self):returnTime.strftime ('%y-%m-%d%h:%m:%s', Time.localtime ())def __init__(self,level=logging. NOTSET): Self.__loggers={} loglevels=Handlers.keys () forLevelinchLoglevels:logger=Logging.getlogger (level)#if level is not specified, the obtained handler appears to be the same handler?Logger.addhandler (Handlers[level]) Logger.setlevel (level) self.__loggers. Update ({Level:logger})defgetlogmessage (self,level,message): Frame,filename,lineno,functionname,code,unknowfield= Inspect.stack () [2] " "log format: [TIME] [type] [record code] information" " return "[%s ] [%s] [%s-%s-%s]%s"%(Self.printfnow (), level,filename,lineno,functionname,message)definfo (self,message): Message= Self.getlogmessage ("Info", message) self.__loggers[Logging.info].info (message)deferror (Self,message): Message= Self.getlogmessage ("Error", message) self.__loggers[Logging. Error].error (message)defWarning (self,message): Message= Self.getlogmessage ("Warning", message) self.__loggers[Logging. Warning].warning (message)defDebug (self,message): Message= Self.getlogmessage ("Debug", message) self.__loggers[Logging. Debug].debug (message)defCritical (self,message): Message= Self.getlogmessage ("Critical", message) self.__loggers[Logging. Critical].critical (message)if __name__=="__main__": Logger=Tnlog () logger.debug ("Debug") Logger=Tnlog () logger.info ("Info") Logger=Tnlog () logger.warning ("Warning") Logger=Tnlog () logger.error ("Error") Logger=Tnlog () logger.critical ("Critical")
Python: Log classes with different levels of log output to different files