【问题标题】:Record traceback into log file (Custom Exception)将回溯记录到日志文件中(自定义异常)
【发布时间】:2021-07-09 02:38:10
【问题描述】:

我想记录我的自定义异常的 Traceback。例如:

main.py:

from error import *
x=int(input("guess a number"))
y=10
if x==y:
    print("corret")
else:
    raise wrong()

error.py:

from datetime import datetime
import os
import logging
class ErrorHandler:
         def log_info(self):
            try:
                os.makedirs('Error Log')
            except OSError:
                pass
            current_datetime = datetime.now()
            current_datetime = current_datetime.strftime("%Y%m%d")
            logging.basicConfig(filename=r"Error log\Errorlog_" + current_datetime + ".log", level=logging.DEBUG)

class wrong(Exception):
        def __init__(self):
            print('wrong')
            current_datetime = datetime.now()
            current_datetime = current_datetime.strftime("%Y%m%d_%H:%M:%S")
            ErrorHandler().log_info()
            logging.exception(current_datetime, exc_info=True)

我在日志中得到的是:

ERROR:root:20210414_11:16:37
NoneType: None

无论如何我可以将 Traceback 记录到日志文件中吗?

【问题讨论】:

    标签: python logging error-handling


    【解决方案1】:

    我用这种方法记录我的回溯

    import traceback
    
    try:
        #trigger Exception
        int("abc")
    except:
        #write full traceback to a file, relative to the script
        f = open("error_log.txt", "w")
        f.write(traceback.format_exc())
        f.close()
    

    创建的日志文件将包含以下信息:

    Traceback (most recent call last):
      File "D:\Path\to\script.py", line 8, in <module>
        int("abc")
    ValueError: invalid literal for int() with base 10: 'abc'
    

    【讨论】:

      猜你喜欢
      • 2020-12-09
      • 2012-10-06
      • 1970-01-01
      • 2022-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多