#-*- coding: utf-8 -*-
importosimporttimefrom logging.handlers importRotatingFileHandlerimportloggingimportinspect
dir= os.path.dirname(__file__)
handlers= {logging.NOTSET: os.path.join(dir, 'notset.log'),
logging.DEBUG: os.path.join(dir,'debug.log'),
logging.INFO: os.path.join(dir,'info.log'),
logging.WARNING: os.path.join(dir,'warning.log'),
logging.ERROR: os.path.join(dir,'error.log'),
logging.CRITICAL: os.path.join(dir,'critical.log'),
}defcreateHandlers():
logLevels=handlers.keys()for level inlogLevels:
path=os.path.abspath(handlers[level])
handlers[level]= RotatingFileHandler(path, maxBytes=10000, backupCount=2, encoding='utf-8')#加载模块时创建全局变量
createHandlers()classTNLog(object):defprintfNow(self):return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())def __init__(self, level=logging.NOTSET):
self.__loggers ={}
logLevels=handlers.keys()for level inlogLevels:
logger=logging.getLogger(str(level))#如果不指定level,获得的handler似乎是同一个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]'''日志格式:[时间] [类型] [记录代码] 信息'''
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.info("info")
logger.warning("warning")
logger.error("error")
logger.critical("critical")