Python--logging模块不同级别写入到不同文件
程序员文章站
2022-05-02 16:45:07
将不同级别的logging 日志信息写入到不同文件 ......
将不同级别的logging 日志信息写入到不同文件
# -*- coding: utf-8 -*- import os import time import logging import inspect from logging.handlers import rotatingfilehandler dir = os.path.dirname(__file__) dir_time = time.strftime('%y-%m-%d', time.localtime()) handlers = {logging.notset: os.path.join(dir, 'notset_%s.log'%dir_time), logging.debug: os.path.join(dir, 'debug_%s.log'%dir_time), logging.info: os.path.join(dir, 'info_%s.log'%dir_time), logging.warning: os.path.join(dir, 'warning_%s.log'%dir_time), logging.error: os.path.join(dir, 'error_%s.log'%dir_time), logging.critical: os.path.join(dir, 'critical_%s.log'%dir_time), } def createhandlers(): loglevels = handlers.keys() for level in loglevels: path = os.path.abspath(handlers[level]) handlers[level] = rotatingfilehandler(path, maxbytes=10000, backupcount=2, encoding='utf-8') # 加载模块时创建全局变量 createhandlers() class tnlog(object): def printfnow(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 in loglevels: logger = logging.getlogger(str(level)) # 如果不指定level,获得的handler似乎是同一个handler? logger.addhandler(handlers[level]) logger.setlevel(level) self.__loggers.update({level: logger}) def getlogmessage(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) def info(self, message): message = self.getlogmessage("info", message) self.__loggers[logging.info].info(message) def error(self, message): message = self.getlogmessage("error", message) self.__loggers[logging.error].error(message) def warning(self, message): message = self.getlogmessage("warning", message) self.__loggers[logging.warning].warning(message) def debug(self, message): message = self.getlogmessage("debug", message) self.__loggers[logging.debug].debug(message) def critical(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")
上一篇: 机器学习----逻辑回归
下一篇: 天猫双11合伙人能量PK怎么才能赢?