我有一个python程序,它利用多处理来提高效率,还有一个为每个进程创建记录器的函数。记录器功能如下所示:
import logging
import os
def create_logger(app_name):
"""Create a logging interface"""
# create a logger
if logging in os.environ:
logging_string = os.environ["logging"]
if logging_string == "DEBUG":
logging_level = loggin.DEBUG
else if logging_string == "INFO":
logging_level = logging.INFO
else if logging_string == "WARNING":
logging_level = logging.WARNING
else if logging_string == "ERROR":
logging_level = logging.ERROR
else if logging_string == "CRITICAL":
logging_level = logging.CRITICAL
else:
logging_level = logging.INFO
logger = logging.getLogger(app_name)
logger.setLevel(logging_level)
# Console handler for error output
console_handler = logging.StreamHandler()
console_handler.setLevel(logging_level)
# Formatter to make everything look nice
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)
# Add the handlers to the logger
logger.addHandler(console_handler)
return logger
我的处理功能如下:
import custom_logging
def do_capture(data_dict_access):
"""Process data"""
# Custom logging
LOGGER = custom_logging.create_logger("processor")
LOGGER.debug("Doing stuff...")
但是,无论日志环境变量设置为什么,我仍然会在控制台中收到调试日志消息。为什么我的日志记录级别没有生效,对setLevel()的调用肯定会阻止调试消息被记录?
答案 0 :(得分:3)
以下是创建记录器对象的简便方法:
import logging
import os
def create_logger(app_name):
"""Create a logging interface"""
logging_level = os.getenv('logging', logging.INFO)
logging.basicConfig(
level=logging_level,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(app_name)
return logger
logging.DEBUG
,logging
模块可以理解这些字符串。basicConfig
可以减轻设置记录器的痛苦。您不需要创建处理程序,设置格式,设置级别......这应该适用于大多数情况。除了else if
之外,我发现了为什么你的代码不起作用。考虑你的行:
if logging in os.environ:
在此行loggging
上没有引用是指logging
库包。你想要的是:
if 'logging' in os.environ: