python - 如何在 Python 日志记录中格式化异常堆栈跟踪?

标签 python logging traceback

我在 Python 中创建的日志旨在临时存储为文件,这些文件将依次处理到日志数据库中。他们采用管道分隔的格式来指示将如何处理日志,但是 logging.exception() 通过添加太多字段和太多换行符打破了我的标准。

import logging
logging.basicConfig(filename='output.txt', 
                    format='%(asctime)s|%(levelname)s|%(message)s|', 
                    datefmt='%m/%d/%Y %I:%M:%S %p', 
                    level=logging.DEBUG)
logging.info('Sample message')

try:
    x = 1 / 0
except ZeroDivisionError as e:
    logging.exception('ZeroDivisionError: {0}'.format(e))

# output.txt
01/27/2015 02:09:01 PM|INFO|Sample message|
01/27/2015 02:09:01 PM|ERROR|ZeroDivisionError: integer division or modulo by zero|
Traceback (most recent call last):
  File "C:\Users\matr06586\Desktop\ETLstage\Python\blahblah.py", line 90, in <module>
    x = 1 / 0
ZeroDivisionError: integer division or modulo by zero

我怎样才能最好地处理或格式化带有空格和换行符的回溯?这些消息是 logging.exception() 中不可分割的一部分。 ,但是当我试图记录异常实例时,绕过该函数感觉很奇怪。我如何记录我的回溯并格式化它们?是否应忽略回溯?

感谢您的宝贵时间!

最佳答案

您可以定义您自己的Formatter,您可以重写其方法来准确地按照您想要的方式格式化异常信息。这是一个简单的(但有效的)示例:

import logging

class OneLineExceptionFormatter(logging.Formatter):
    def formatException(self, exc_info):
        result = super(OneLineExceptionFormatter, self).formatException(exc_info)
        return repr(result) # or format into one line however you want to

    def format(self, record):
        s = super(OneLineExceptionFormatter, self).format(record)
        if record.exc_text:
            s = s.replace('\n', '') + '|'
        return s

fh = logging.FileHandler('output.txt', 'w')
f = OneLineExceptionFormatter('%(asctime)s|%(levelname)s|%(message)s|', '%m/%d/%Y %I:%M:%S %p')
fh.setFormatter(f)
root = logging.getLogger()
root.setLevel(logging.DEBUG)
root.addHandler(fh)
logging.info('Sample message')

try:
    x = 1 / 0
except ZeroDivisionError as e:
    logging.exception('ZeroDivisionError: {0}'.format(e))

这只产生两行:

01/28/2015 07:28:27 AM|INFO|Sample message|
01/28/2015 07:28:27 AM|ERROR|ZeroDivisionError: integer division or modulo by zero|'Traceback (most recent call last):\n  File "logtest2.py", line 23, in <module>\n    x = 1 / 0\nZeroDivisionError: integer division or modulo by zero'|

当然,您可以在此示例的基础上精确地执行您想要的操作,例如通过 traceback 模块。

关于python - 如何在 Python 日志记录中格式化异常堆栈跟踪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28180159/

相关文章:

python - 从 Python 管理与 redis 的连接

c# - 记录带有可变数量的 printf 样式参数的消息

ios - iOS >= 8 使用 os_log 和 NSLog 的快速日志记录

python - 在 python 中写入文件并获取权限拒绝

Python Discord 机器人故障排除

Python 脚本在继续之前等待外部命令完成

python - Jupyter Lab交互式绘图: unsupported operand type(s) for *: 'FloatSlider' and 'float'

ruby-on-rails - 如何使 Rails.logger.debug 打印哈希更具可读性

错误处理后 while 循环中的 Python 回溯错误

python - python 中的回溯对象