繁体   English   中英

如何将未处理的错误放入日志文件 - Python logging

[英]How to put unhandled errors into a log file - Python logging

我正在尝试将各种错误记录到日志文件中。 (未处理的异常未记录到日志文件中。)

例如在我的 function 里面我有:

i = "hello"
x = i /3

给出TypeError: unsupported operand type(s) for /: 'str' and 'int'

我想将此错误放入日志文件中,而不必在我的函数中添加预定义的logger.error行,因为我不知道在运行时可能会遇到什么错误。 希望我说得有道理。

我尝试了很多搜索,但找不到这个问题的任何答案

我试过

print = logger.info

但事实证明它没用,因为它对错误没有帮助,而且我知道这是一种糟糕的代码编写方式

到目前为止我的代码:

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

c_format = logging.Formatter('%(name)s:%(funcName)s - %(levelname)s - %(message)s')
f_format = logging.Formatter('%(asctime)s - [%(levelname)s] -[%(name)s:%(funcName)s:%(lineno)d]- %(message)s', datefmt='%d-%b-%y %H:%M:%S')

LOG_FILENAME = 'check.log'
LOG_FILENAME = os.path.join(get_datadir_path(), LOG_FILENAME)
f_handler = logging.FileHandler(LOG_FILENAME) 
f_handler.setFormatter(f_format)
f_handler.setLevel(logging.DEBUG)

c_handler = logging.StreamHandler(sys.stdout)
c_handler.setFormatter(c_format)
c_handler.setLevel(logging.DEBUG)


logger.addHandler(c_handler)
logger.addHandler(f_handler)

我在这里先向您的帮助表示感谢

使用tryexceptlogger.exception

try:
    i = "hello"
    x = i / 3
except Exception as e:
    logger.exception('Exception!')
    raise  # you can also raise the exception to stop running after logging

except Exception将捕获所有非退出异常(但它是一个过于宽泛的异常子句)。 或者使用except BaseException来捕获各种异常,例如KeyboardInterrupt

然后将异常记录到您的日志文件中:

01-Jan-23 22:33:48 - [ERROR] -[root:<module>:29]- Exception!
Traceback (most recent call last):
  File "/data/xxx.py", line 27, in <module>
    x = i / 3
TypeError: unsupported operand type(s) for /: 'str' and 'int'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM