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

标签 python-2.7 logging unicode

我正在尝试在 Win 8 上使用 Python 2.7 创建一个 utf-8 日志文件。我总是收到 UnicodeDecodeError: 'ascii' codec can't Decode byte 0xfc inposition 20: ordinal not in range (128) 当我尝试记录其中包含非拉丁字符的 Windows 路径时。以下设置总是会抛出可怕的 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) 中,但没有帮助。我已经无计可施了。如何记录这些棘手的路径?

最佳答案

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

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

关于python-2.7 - 在 Python 中将 str 消息插入 Unicode 日志模板时出现 UnicodeDecodeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41529114/

相关文章:

asp.net - 用于将非英文字符存储到 SQL 数据库的 HTML/ASPX 文本框

unicode - FreeBSD 设置为 UTF-8,但似乎以 ASCII 显示

python - 使用 str.format 截断字符串的开头

logging - 主管不写更多的日志

c++ - 在创建应用程序时记录应用程序的事件并使用 Visual Studio C++ 进行测试

java - 为什么 "\400"不是编译时错误?

python - 使用函数输出作为另一个函数的输入

python - 使用 nolearn-DBN 分类器时,“garray”对象没有属性 'size'

Python 将嵌套循环转换为简单行

php - 如何在PHP中记录调用当前函数的文件/行的名称?