问题描述
在Windows 10上,日志记录模块发送此错误(使用scrapy)
On Windows 10 the logging module send this error (using scrapy)
# --- Logging error ---
...
# UnicodeEncodeError: 'charmap' codec can't encode characters in position 175-176: character maps to <undefined>
根据 tuto (不需要).
According to the tuto it isnt needed.
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的问题(或与日志记录模块无关).而且日志记录教程甚至不谈论utf-8. (请注意,我可以毫无问题地打印UTF8字符.问题仅在日志记录模块中出现)
I found many questions on the topics, but mostly on python 2 (or not related to the logging module). And the logging tutorial don't even talk about utf-8. (Notice that I can print UTF8 characters without any problem. The problem only occur with the logging module)
推荐答案
我没有使用Scrapy
,但是在香草Python 3.6日志记录中遇到了同样的问题,即无法通过到一个文件(控制台正常工作).
I'm not using Scrapy
but I ran into the same issue with vanilla Python 3.6 logging of not being able to write UTF-8 characters via logging
to a file (console worked just fine).
基于此评论我在FileHandler
初始化.我正在通过INI文件配置日志记录,如下所示:
Based on this comment I added 'utf-8'
to my FileHandler
initialization. I'm configuring logging via an INI file so it looks like this:
[handler_file]
class = FileHandler
args = (r'log.txt', 'a', 'utf-8')
level = NOTSET
formatter = generic
要使用logging.basicConfig()
,我认为您应该能够执行以下操作:
To use logging.basicConfig()
I think that you should be able to do the following:
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
)
这篇关于python 3.6 *记录模块错误* UnicodeEncodeError:"charmap"编解码器无法编码字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!