【问题标题】:python 3.6 *logging modul error* UnicodeEncodeError: 'charmap' codec can't encode characterspython 3.6 *记录模块错误* UnicodeEncodeError:'charmap'编解码器无法编码字符
【发布时间】:2018-03-20 01:24:18
【问题描述】:

在 Windows 10 上,日志记录模块发送此错误(使用 scrapy)

# --- Logging error ---
...
# UnicodeEncodeError: 'charmap' codec can't encode characters in position 175-176: character maps to <undefined>

我已经读到我应该添加encoding='utf-8',但我没有找到如何在下面的代码中添加它。 编辑:根据the tuto,它不需要。

configure_logging(install_root_handler=False) #override default log settings
logging.basicConfig(
    filename='logfile.log',
    format='%(levelname)s: %(message)s',
    datefmt='%m-%d %H:%M',
    level=logging.INFO #CRITICAL ERROR WARNING  INFO    DEBUG    NOTSET 
)

我发现了很多关于这些主题的问题,但主要是关于 python 2(或not related to the logging module)。日志教程甚至不谈论 utf-8。 (请注意,我可以毫无问题地打印 UTF8 字符。问题仅出现在日志记录模块上)

【问题讨论】:

    标签: python-3.x logging encoding character-encoding error-logging


    【解决方案1】:

    我没有使用 Scrapy,但我遇到了与 vanilla Python 3.6 日志记录相同的问题,即无法通过 logging 将 UTF-8 字符写入文件(控制台工作得很好)。

    基于this comment,我将'utf-8' 添加到我的FileHandler 初始化中。我正在通过 INI 文件配置日志记录,所以它看起来像这样:

    [handler_file]
    class = FileHandler
    args = (r'log.txt', 'a', 'utf-8')
    level = NOTSET
    formatter = generic
    

    要使用logging.basicConfig(),我认为你应该能够做到以下几点:

    configure_logging(install_root_handler=False) #override default log settings
    logging.basicConfig(
        handlers=[logging.FileHandler('logfile.log', 'w', 'utf-8')],
        format='%(levelname)s: %(message)s',
        datefmt='%m-%d %H:%M',
        level=logging.INFO #CRITICAL ERROR WARNING  INFO    DEBUG    NOTSET 
    )
    

    【讨论】:

    • logging.basicConfig() 的答案对我不起作用。
    • @SomJura,你能再具体一点吗?我刚刚在 Python 3.8 上尝试过,它似乎可以工作(我确实跳过了 configure_logging() 调用)。
    • 它似乎不起作用,因为我使用的是import logging,对于较新版本的 Python 不再需要。
    • 在windows中可以吗?面对同样的问题,我尝试了上述解决方案,但它不起作用。我正在使用 Python 3.8.10。我尝试删除导入语句“导入日志记录”,但这会导致错误。 'NameError: name 'logging' is not defined'
    • @Abhi,我最初在 Windows 中遇到了这个问题,所以它应该在 Windows 中工作。你有什么错误?查看第二个logging.basicConfig() 示例,我不确定configure_logging() 的第一行在那里做什么,如果你删除它怎么办?你需要import logging
    猜你喜欢
    • 2015-01-21
    • 2016-09-22
    • 1970-01-01
    相关资源
    最近更新 更多