pythonlogging.ritic() 引发异常并转储堆栈跟踪并死亡

Mor*_*enB 1 logging exception python-3.x

我正在从 perl (log4perl) 和 java (slf4j) 移植一些代码。一切都很好,除了logging.ritic() 不会像其他框架中那样转储堆栈跟踪并死掉,需要添加大量额外的代码,logger.exception() 也只写入错误。

今天我这样做:

try:
    errmsg = "--id={} not found on --host={}".format(args.siteid, args.host)
    raise GX8Exception(errmsg)
except GX8Exception as e:
    log.exception(e)
    sys.exit(-1)
Run Code Online (Sandbox Code Playgroud)

这会产生:

2018-01-10 10:09:56,814 [ERROR   ] root         --id=7A4A7845-7559-4F89-B678-8ADFECF5F7C3 not found on --host=welfare-qa
Traceback (most recent call last):
  File "./gx8-controller.py", line 85, in <module>
    raise GX8Exception(errmsg)
GX8Exception: --id=7A4A7845-7559-4F89-B678-8ADFECF5F7C3 not found on --host=welfare-qa
Run Code Online (Sandbox Code Playgroud)

有没有办法配置 pythonmodule 记录器来执行此操作,或任何其他框架来执行相同的操作:

log.critical("--id={} not found on --host={}".format(args.siteid, args.host))
Run Code Online (Sandbox Code Playgroud)

Nat*_*eks 6

一种方法是创建一个自定义处理程序,该处理程序除了将日志消息传递到其超级级之外什么都不做,然后在日志级别足够高时退出:

import logging

class ExitOnExceptionHandler(logging.StreamHandler):
    def emit(self, record):
        super().emit(record)
        if record.levelno in (logging.ERROR, logging.CRITICAL):
            raise SystemExit(-1)


logging.basicConfig(handlers=[ExitOnExceptionHandler()], level=logging.DEBUG)

logger = logging.getLogger('MYTHING')

def causeAProblem():
    try:
        raise ValueError("Oh no!")
    except Exception as e:
        logger.exception(e)

logger.warning('Going to try something risky...')
causeAProblem()
print("This won't get printed")
Run Code Online (Sandbox Code Playgroud)

输出:

import logging

class ExitOnExceptionHandler(logging.StreamHandler):
    def emit(self, record):
        super().emit(record)
        if record.levelno in (logging.ERROR, logging.CRITICAL):
            raise SystemExit(-1)


logging.basicConfig(handlers=[ExitOnExceptionHandler()], level=logging.DEBUG)

logger = logging.getLogger('MYTHING')

def causeAProblem():
    try:
        raise ValueError("Oh no!")
    except Exception as e:
        logger.exception(e)

logger.warning('Going to try something risky...')
causeAProblem()
print("This won't get printed")
Run Code Online (Sandbox Code Playgroud)

但是,这可能会导致代码用户出现意外行为。如果您想记录异常并退出,则简单地让异常不被捕获,这会更直接。如果您想记录回溯并在代码当前调用的地方退出logging.critical,请将其更改为引发异常。