7

我有一个 python 脚本,它每 10 分钟向我发送一封电子邮件,所有内容都写在控制台中。我在我的 ubuntu 18.04 vps 中使用 crontab 运行它。有时它不发送邮件,所以我假设发生错误时执行停止,但我怎样才能将错误写入 txt 文件以便分析错误?

4

2 回答 2

8

记录模块

为了演示该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

于 2019-03-14T18:54:41.967 回答
1

您可以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)"
于 2019-03-14T18:28:43.783 回答