关于在Python中将str消息插入到Unicode日志记录模板的UnicodeDecodeError

时间:2017-01-08 03:15:05

标签: python-2.7 logging unicode

我试图在Win 8上使用Python 2.7创建一个utf-8日志文件。当我尝试记录包含非Windows的Windows路径时,我总是得到UnicodeDecodeError: 'ascii' codec can't decode byte 0xfc in position 20: ordinal not in range(128) - 中的明字字符。以下设置总是抛出可怕的UnicodeDecodeError

import logging
from logging import handlers

def GetLogger():
    logger = logging.getLogger('log')
    if not len(logger.handlers):
        logger.setLevel(logging.DEBUG)
        logger.propagate = False
        # create a file handler
        fileHandler = logging.handlers.TimedRotatingFileHandler('mylog.log', when = 'midnight', backupCount = 10, encoding = 'utf-8')
        fileHandler.setLevel(logging.DEBUG)
        # unicode template here
        fileHandler.setFormatter(logging.Formatter(u'[%(levelname)-8s: %(asctime)s - %(filename)s:%(lineno)s - %(funcName)s()] - %(message)s'))
        logger.addHandler(fileHandler)
    return logger

logger = GetLogger()
path = 'e:\\\xcf\xf0\xee' + 'foo.bar' # actually I'm just calling os.getcwd() + 'foo.bar' here, and that's what it returns
print type(path) # prints <type 'str'>
logger.warning('Didn\'t find path %s' % path) # <- POOF!
# logger.warning('Didn\'t find path %s' % 'abcde') <- This would work

我尝试在path中包装unicode(path),但它没有帮助。我的智慧结束了。如何记录这些棘手的路径?

1 个答案:

答案 0 :(得分:2)

调用os.getcwdu()获取当前路径的Unicode版本,并在logger.warning中使用Unicode字符串。

处理Unicode时,最好对所有文本使用Unicode字符串,或者使用Python 3.x,它成为'xxxx'的默认类型,b'xxxx'的语法是字节串。您还可以在Python 2.7中使用from __future__ import unicode_literals来模仿Python 3.x行为。有关详细信息,请参阅PEP 3112