有这样的代码:
raise Exception(u'щ')
Caused:
File "/usr/lib/python2.7/logging/__init__.py", line 467, in format
s = self._fmt % record.__dict__
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)
发生这种情况是因为格式字符串是字节字符串,而某些格式字符串参数是带有非 ASCII 字符的 unicode 字符串:
>>> "%(message)s" % {'message': Exception(u'\u0449')}
*** UnicodeEncodeError: 'ascii' codec can't encode character u'\u0449' in position 0: ordinal not in range(128)
使格式字符串 unicode 可以解决该问题:
>>> u"%(message)s" % {'message': Exception(u'\u0449')}
u'\u0449'
因此,在您的日志记录配置中,将所有格式字符串设置为 unicode:
'formatters': {
'simple': {
'format': u'%(asctime)-s %(levelname)s [%(name)s]: %(message)s',
'datefmt': '%Y-%m-%d %H:%M:%S',
},
...
并修补默认值logging
使用 unicode 格式字符串的格式化程序:
logging._defaultFormatter = logging.Formatter(u"%(message)s")