在python 2中正确记录unicode和utf-8异常

Jör*_*ees 7 python unicode logging utf-8 python-2.7

我试图在python 2.7中记录库中的各种异常.我发现有时异常包含unicode字符串,有时包含utf8字节字符串.我认为这logging.exception(e)是记录它们的正确方法,但以下似乎不起作用:

# encoding: utf-8
import logging
try:
    raise Exception('jörn')
except Exception as e:
    logging.exception(e)

try:
    raise Exception(u'jörn')
except Exception as e:
    logging.exception(e)
Run Code Online (Sandbox Code Playgroud)

将其保存到文件中并运行它会导致:

$ python test.py
ERROR:root:jörn
Traceback (most recent call last):
  File "test.py", line 4, in <module>
    raise Exception('jörn')
Exception: jörn
Traceback (most recent call last):
  File "/usr/local/Cellar/python/2.7.10/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 859, in emit
    msg = self.format(record)
  File "/usr/local/Cellar/python/2.7.10/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 732, in format
    return fmt.format(record)
  File "/usr/local/Cellar/python/2.7.10/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 474, in format
    s = self._fmt % record.__dict__
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 1: ordinal not in range(128)
Logged from file test.py, line 12
Run Code Online (Sandbox Code Playgroud)

因此,当您看到utf8异常正常工作时,但unicode异常打破了日志记录,吞噬了真正的异常并将其隐藏在后面UnicodeEncodeError.

是否有一些标准的日志工具用于不会破坏我的代码的异常?我错过了什么?

Ber*_*ard 3

不是日志记录无法处理 unicode,而是 Exception.__str__ 方法不支持 unicode 字符串作为异常参数。当您调用它时,logging.exception(e)它将执行类似的操作,而该操作又会在异常实例上logging.exception(str(e))执行类似的操作。str(self.args)这就是错误的来源,你的 self.args 是一个 unicode 字符串,不能用 ascii 编码。您有两个选择,要么执行logging.exception(unicode(e)),要么实现您自己的异常类,该类提供__str__可以处理 self.args 中的 unicode 对象的方法。

第一次测试通过的原因是编辑器将字符串编码为 UTF-8,并且 Python 看到一个带有编码的 unicode 字符的字符串实例。