Python多个记录器不工作。如何配置具有不同级别的多个记录器?

2024-05-29 10:58:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试配置两个记录器,一个用于信息级别,另一个用于调试级别。我希望调试内容只转到我的日志文件,我希望信息内容转到日志文件和控制台。请参阅下面的代码。我的文件中没有写入任何内容,控制台中也没有显示任何内容

logFileDir = os.path.join(os.getcwd(), '.logs')
if not os.path.exists(logFileDir):
    os.mkdir(logFileDir)
infoLogFileDir = os.path.join(logFileDir, 'INFO')
if not os.path.exists(infoLogFileDir):
    os.mkdir(infoLogFileDir)
debugLogFileDir = os.path.join(logFileDir, 'DEBUG')
if not os.path.exists(debugLogFileDir):
    os.mkdir(debugLogFileDir)
LOG_FORMAT = ("%(asctime)s [%(levelname)s]: %(message)s in %(pathname)s:%(lineno)d")

#DEBUG LOGGER
debugLogFileName = os.path.join(debugLogFileDir, 'EFDebugLog.log')
debugLogger = logging.getLogger("debugLogger")
debugLogger.setLevel(logging.DEBUG)
debugHandler = logging.handlers.RotatingFileHandler(filename=debugLogFileName,maxBytes=5000000, backupCount=100)
debugHandler.setLevel(logging.DEBUG)
debugHandler.setFormatter(Formatter(LOG_FORMAT))
debugLogger.addHandler(debugHandler)

#INFO LOGGER
infoLogFileName = os.path.join(infoLogFileDir, 'EFInfoLog.log')
infoLogger = logging.getLogger("infoLogger")
infoLogger.setLevel(logging.INFO)
infoHandler = logging.handlers.RotatingFileHandler(filename=infoLogFileName,maxBytes=5000000, backupCount=100)
infoHandler.setLevel(logging.INFO)
infoHandler.setFormatter(Formatter(LOG_FORMAT))
infoLogger.addHandler(infoHandler)
infoLogger.addHandler(logging.StreamHandler())

Tags: pathdebuginfo内容osloggingjoinsetlevel
1条回答
网友
1楼 · 发布于 2024-05-29 10:58:40

正在向根记录器调用log的logging.*函数。这就是为什么你看不到任何输出;您尚未为根记录器配置任何处理程序。您只为自己的记录器配置了处理程序,而您没有使用这些处理程序

如果要使用logging.*函数,首先需要配置根记录器,无需任何参数即可通过调用getLogger获得根记录器。因此,代码可能如下所示:

import logging
import logging.handlers


root_logger = logging.getLogger()

info_handler = logging.handlers.RotatingFileHandler(filename='infolog.txt')
info_handler.setLevel(logging.INFO)

stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)

debug_handler = logging.handlers.RotatingFileHandler(filename='debuglog.txt')
debug_handler.setLevel(logging.DEBUG)

root_logger.addHandler(stream_handler)
root_logger.addHandler(debug_handler)
root_logger.addHandler(info_handler)

# this is needed, since the severity is WARNING by default,
# i.e. it would not log any debug messages
root_logger.setLevel(logging.DEBUG)

root_logger.debug('this is a debug message')
root_logger.info('this is an info message')



相关问题 更多 >

    热门问题