在Python中记录异常时出现UnicodeDecodeError [英] UnicodeDecodeError when logging an Exception in Python

查看:479
本文介绍了在Python中记录异常时出现UnicodeDecodeError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python 2.7.9.在Win7 x64上为x32.

I'm using Python 2.7.9. x32 on Win7 x64.

当我记录包含Umlauts的异常时,我总是收到
UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 39: ordinal not in range(128)

When I'm logging an Exception containing Umlauts, I always receive
UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 39: ordinal not in range(128)

我的示例代码是:

except Exception as e:
            logging.error('Error loading SCMTool for repository '
                          '%s (ID %d): %s' % (repo.name, repo.id, e),
                          exc_info=1)

正在记录的异常为WindowsError: [Error 267] Der Verzeichnisname ist ungültig. 该问题基于"ung Ü ltig"变音符号.

The Exception being logged is WindowsError: [Error 267] Der Verzeichnisname ist ungültig. The Problem is based on the "ungÜltig" umlaut.

删除最后一个%se后,它可以正常工作.

After removing the last %s and the e it works without a problem.

每次记录异常时都会发生这种情况,因此更改每个记录器是无可替代的.

This happens everytime an exception is logged, therefore changing every logger is no alternative.

有人知道如何使Exception在全局范围内返回unicode字符串吗?

Does anyone have an idea how to make Exception return a unicode string globally?

推荐答案

您正试图将unicode对象插入到str模板中,从而触发隐式编码.

You are trying to interpolate a unicode object into a str template, triggering an implicit encoding.

使用unicode模板; logging可以很好地处理Unicode:

Use a unicode template; logging can handle Unicode just fine:

logging.error(u'Error loading SCMTool for repository '
              '%s (ID %d): %s' % (repo.name, repo.id, e),
              exc_info=1)

另外两个提示:

  • 您不必自己进行插值;如果您将3个元素作为单独的参数进行插值,则logging将为您插值,但前提是确实要发出该消息.

  • You don't have to do the interpolation yourself; if you pass in the 3 elements to interpolate as separate arguments, logging will interpolate for you, but only if the message is actually going to be emitted.

如果使用logging.exception(),则消息将记录在ERROR级别,并且已为您设置了exc_info.它可以获得相同的结果,但是在以后阅读代码时更容易识别.无论哪种方式,在这种情况下都已经已包含,因此无需在消息中再次包含它.

If you use logging.exception() the message is logged at the ERROR level and exc_info is set for you; it gets you the same result but is more easily recognised when reading your code later. Either way, the exception is already included in that case, no need to include it again in the message.

因此,我将使用:

logging.exception(
    'Error loading SCMTool for repository %s (ID %d)',
    repo.name, repo.id)

这篇关于在Python中记录异常时出现UnicodeDecodeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆