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



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

例如,在我的函数中,我有:

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)

谢谢你的帮助

使用try,exceptlogger.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'

最新更新