Python 2.7 UnicodeDecodeError在Python中将str消息插入Unicode日志模板时出错

Python 2.7 UnicodeDecodeError在Python中将str消息插入Unicode日志模板时出错,python-2.7,logging,unicode,Python 2.7,Logging,Unicode,我正在尝试在Win8上使用Python2.7创建一个utf-8日志文件。当我试图记录包含非拉丁字符的Windows路径时,我总是得到UnicodeDecodeError:“ascii”编解码器无法解码位置20处的字节0xfc:序号不在范围(128)。以下设置总是抛出可怕的UnicodeDecodeError: import logging from logging import handlers def GetLogger(): logger = logging.getLogger('

我正在尝试在Win8上使用Python2.7创建一个utf-8日志文件。当我试图记录包含非拉丁字符的Windows路径时,我总是得到
UnicodeDecodeError:“ascii”编解码器无法解码位置20处的字节0xfc:序号不在范围(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
导入日志
从日志记录导入处理程序
def GetLogger():
logger=logging.getLogger('log')
如果不是len(logger.handlers):
logger.setLevel(logging.DEBUG)
logger.propagate=False
#创建一个文件处理程序
fileHandler=logging.handlers.TimedRotatingFileHandler('mylog.log',when='midnight',backupCount=10,encoding='utf-8')
fileHandler.setLevel(logging.DEBUG)
#unicode模板在这里
fileHandler.setFormatter(logging.Formatter(u'[%(levelname)-8s:%(asctime)s-%(filename)s:%(lineno)s-%(funcName)s()]-%(message)s'))
logger.addHandler(fileHandler)
返回记录器
logger=GetLogger()
path='e:\\\xcf\xf0\xee'+'foo.bar'\\实际上我只是在这里调用os.getcwd()+'foo.bar',这就是它返回的结果
打印类型(路径)#打印
logger.warning('未找到路径%s'%path)调用当前路径的Unicode版本的
os.getcwdu()
,并在
记录器中使用Unicode字符串。warning


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

您是否尝试过
path=u'e:\\\xcf\xf0\xee'+u'foo.bar'