Python logging sys.exit('message')



我遵循这个指南来学习如何利用Python的logging模块。

现在我的每个.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"]
    }
}

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

相关内容

  • 没有找到相关文章

最新更新