📜  如何记录Python异常?

📅  最后修改于: 2022-05-13 01:55:06.163000             🧑  作者: Mango

如何记录Python异常?

要在Python中记录异常,我们可以使用logging模块,通过它我们可以记录错误。

日志记录模块提供了一组简单的日志记录功能,并用于以下目的

  • 调试
  • 信息
  • 警告
  • 错误
  • 危急

在Python中记录带有错误的异常可以在logging.exception()方法中完成。此函数在此记录器上记录级别为 ERROR 的消息。参数被解释为 debug()。异常信息被添加到日志消息中。此方法只能从异常处理程序中调用。

请参阅以下代码以获得更清晰的信息:

示例 1:

Python3
# importing the module
import logging
 
try:
    printf("GeeksforGeeks")
except Exception as Argument:
    logging.exception("Error occurred while printing GeeksforGeeks")


Python3
# importing the module
import logging
 
try:
    printf("GeeksforGeeks")
except Exception as Argument:
 
     # creating/opening a file
     f = open("demofile2.txt", "a")
 
     # writing in the file
     f.write(str(Argument))
      
     # closing the file
     f.close()


输出 :

ERROR:root:Error occurred while printing GeeksforGeeks
Traceback (most recent call last):
  File "/home/gfg.py", line 3, in 
    printf("GeeksforGeeks")
NameError: name 'printf' is not defined

示例2:我们也可以通过以下方法将错误消息记录到不同的文件中而不在控制台中显示错误:

Python3

# importing the module
import logging
 
try:
    printf("GeeksforGeeks")
except Exception as Argument:
 
     # creating/opening a file
     f = open("demofile2.txt", "a")
 
     # writing in the file
     f.write(str(Argument))
      
     # closing the file
     f.close()

错误信息将存储在与代码相同目录下的文件名demofille2.txt中。

输出 :

Traceback (most recent call last):
  File "/home/gfg.py", line 5, in 
    printf("GeeksforGeeks")
NameError: name 'printf' is not defined