生成logger对象,在其他python文件中引用非常方便,代码如下:
# -*- coding: utf-8 -*-
import logging
from concurrent_log_handler import ConcurrentRotatingFileHandler
# 系统日志级别 5选1
LOGGER_LEVEL = logging.DEBUG
#LOGGER_LEVEL = logging.INFO
#LOGGER_LEVEL = logging.WARN
#LOGGER_LEVEL = logging.ERROR
#LOGGER_LEVEL = logging.CRITICAL
def get_logger( filename=None, log_level=LOGGER_LEVEL, max_bytes=50000000, bk_cnt=22 ) :
# 1、获取logger对象
logger = logging.getLogger()
# 2、设置告警等级,大于等于此等级就告警
logger.setLevel(log_level)
# 3、在一个进程中,logger对象是共用的,如果在之前已经设置过,就直接返回,防止多个python文件重复设置,如果重复下边的第4步,会增加多个输出模块,导致数据输出多份。
if len(logger.handlers) != 0 :
return logger
if filename == None :
filename = "mylog.log"
# 4、设置日志格式
handler = ConcurrentRotatingFileHandler( filename, maxBytes=max_bytes, backupCount=bk_cnt )
formatter = logging.Formatter("%(asctime)s - pid:%(process)d %(filename)s:%(funcName)s(%(lineno)s) - %(levelname)s : %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)
# 5、返回此对象
return logger
logger=get_logger()
if "__main__" == __name__ :
logger.debug("dddddddddddddd")
logger.info("iiiiiiiiiiiii")
logger.error("eeeeeeeeeeee")
logger.critical("ccccccccccccc")
测试结果如下,日志等级为INFO,所以DEBUG级别的不展示:

发表回复