我关注如何利用Python的logging
模块{/ 3}}。
现在,我的每个.py文件都通过调用
来获取其记录器logger = logging.getLogger(__name__)
主.py文件设置日志记录读取json配置文件。
import os
import json
import logging.config
def setup_logging(
default_path='logging.json',
default_level=logging.INFO,
env_key='LOG_CFG'
):
path = default_path
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(path):
with open(path, 'rt') as f:
config = json.load(f)
logging.config.dictConfig(config)
else:
logging.basicConfig(level=default_level)
setup_logging()
但是,我有很多代码没有正确记录而只是在退出之前打印出错误消息。
# when error occurs
sys.exit('error message')
我想知道是否有捕获这些错误的方法,以与其他错误(带时间戳)相同的方式格式化它们并将它们保存在使用的同一个error.log
文件中记录器。
这是我的配置文件logging.json
{
"version": 1,
"disable_existing_loggers": false,
"formatters": {
"simple": {
"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"level": "DEBUG",
"formatter": "simple",
"stream": "ext://sys.stdout"
},
"info_file_handler": {
"class": "logging.handlers.RotatingFileHandler",
"level": "INFO",
"formatter": "simple",
"filename": "info.log",
"maxBytes": 10485760,
"backupCount": 20,
"encoding": "utf8"
},
"error_file_handler": {
"class": "logging.handlers.RotatingFileHandler",
"level": "ERROR",
"formatter": "simple",
"filename": "errors.log",
"maxBytes": 10485760,
"backupCount": 20,
"encoding": "utf8"
}
},
"loggers": {
"my_module": {
"level": "ERROR",
"handlers": ["console"],
"propagate": false
}
},
"root": {
"level": "DEBUG",
"handlers": ["console", "info_file_handler", "error_file_handler"]
}
}
答案 0 :(得分:6)
由于sys.exit是通过引发SystemExit异常来实现的,因此您可以捕获异常并将其记录下来:
import logging
import sys
import os
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger('example')
def function_will_exit():
sys.exit('some error log')
try:
function_will_exit()
except SystemExit as e:
# this log will include traceback
logger.exception('function_will_exit failed with exception')
# this log will just include content in sys.exit
logger.error(str(e))
# if you don't need exception traceback from Python
# os._exit(1)
raise