执行并自动将所有错误消息存储到文件中



有没有一种简单的方法来执行python脚本,然后将所有错误消息保存到一种日志文件(csv,txt,任何东西(。

class MyClass():
def __init__(self, something):
self.something = something
def my_function(self):
# code here

还是在任何地方添加 try 和 except 语句并将错误消息写入文件的唯一方法?

是的,您可以使用python日志记录来做到这一点

下面是一个特定示例,将 https://realpython.com/python-logging/中的信息与代码一起使用:

import logging
logging.basicConfig(filename='app.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')
logging.warning('This will get logged to a file')
class MyClass():
def __init__(self, something):
self.something = something
def my_function(self):
logging.warning('my_function entered...')

实例化类并调用my_function后,您应该在日志文件中获取日志记录输出(此处 app.log(:

root - WARNING - This will get logged to a file
root - WARNING - my_function entered...

最新更新