Python:如何在txt文件的控制台中写入错误? [英] Python: How to write error in the console in txt file?
问题描述
我有一个 python 脚本,它每 10 分钟向我发送一封电子邮件,其中包含在控制台中编写的所有内容.我在我的 ubuntu 18.04 vps 中使用 crontab 运行它.有时它不发送邮件,所以我假设当发生错误时执行会停止,但如何将错误写入 txt 文件中以便我可以分析错误?
I have a python script which every 10 minutes sends me an email with everything written in the console. I am running this with the crontab in my ubuntu 18.04 vps. Sometimes it doesn't send the mail so I assume that when an error happens execution stops but how can I get the errors to be written in a txt file so I can analyze the error ?
推荐答案
日志模块
Logging Module
To demonstrate the approach with the logging
module, this would be the general approach
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
来完成这个(我不确定你会因此而鼓掌)
Print to File
As I pointed out in the comments, you could accomplish this with print
as well (I'm not sure you will be applauded for it)
# 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
包括在这种情况下的回溯,这是该模块的众多巨大好处之一
Note that logging.exception
includes the traceback in this case, which is one of the many huge benefits of that module
为了完整起见,traceback
模块利用与 print
类似的方法,您可以在其中提供文件句柄:
In the interest of completeness, the traceback
module leverages a similar approach as print
, where you can supply a file handle:
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
这篇关于Python:如何在txt文件的控制台中写入错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!