我有一个python脚本,每10分钟发送一封电子邮件,其中包含在控制台中写的所有内容。我在我的ubuntu 18.04 vps中用crontab运行它。有时它不发送邮件所以我假设当错误发生时执行停止但我如何才能将错误写入txt文件以便我可以分析错误?
为了演示使用logging
模块的方法,这将是一般方法
import logging
# Create a logging instance
logger = logging.getLogger('my_application')
logger.setLevel(logging.INFO) # you can set this to be DEBUG, INFO, ERROR
# Assign a file-handler to that instance
fh = logging.FileHandler("file_dir.txt")
fh.setLevel(logging.INFO) # again, you can set this differently
# Format your logs (optional)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter) # This will set the format to the file handler
# Add the handler to your logging instance
logger.addHandler(fh)
try:
raise ValueError("Some error occurred")
except ValueError as e:
logger.exception(e) # Will send the errors to the file
如果我cat file_dir.txt
2019-03-14 14:52:50,676 - my_application - ERROR - Some error occurred
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ValueError: Some error occurred
正如我在评论中指出的那样,你也可以用print
完成这个任务(我不确定你会为它鼓掌)
# Set your stdout pointer to a file handler
with open('my_errors.txt', 'a') as fh:
try:
raise ValueError("Some error occurred")
except ValueError as e:
print(e, file=fh)
cat my_errors.txt
Some error occurred
请注意,logging.exception
在这种情况下包含回溯,这是该模块的众多巨大好处之一
为了完整性,traceback
模块采用与print
类似的方法,您可以在其中提供文件句柄:
import traceback
import sys
with open('error.txt', 'a') as fh:
try:
raise ValueError("Some error occurred")
except ValueError as e:
e_type, e_val, e_tb = sys.exc_info()
traceback.print_exception(e_type, e_val, e_tb, file=fh)
这将包括您想要的所有logging
信息
您可以使用评论中建议的logging
模块(可能超出我的知识范围),或者使用try
和except
捕获错误,如:
try:
pass
#run the code you currently have
except Exception as e: # catch ALLLLLL errors!!!
print(e) # or more likely you'd want something like "email_to_me(e)"
虽然这通常不赞成捕获所有异常,因为如果你的程序失败,无论出于什么原因它都会被except
条款吞噬,所以更好的方法是找出你遇到的特定错误,如IndexError
,然后抓住这个具体错误如:
try:
pass
#run the code you currently have
except IndexError as e: # catch only indexing errors!!!
print(e) # or more likely you'd want something like "email_to_me(e)"