读取Python日志文件的Unicode错误(日志记录)

时间:2015-01-13 19:47:34

标签: python logging unicode

我正在使用Pythons日志库创建一个日志文件。当我尝试用python阅读它并在html页面上打印它(使用Flask)时,我得到:

<textarea cols="80" rows="20">{% for line in log %}{{line}}{% endfor %}
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 36: ordinal not in range(128)

我猜这与日志文件在其他解码中被解码有关,但是哪个?

这是设置日志文件的行,如果它有帮助:

fileLogger = logging.handlers.TimedRotatingFileHandler(filename = 'log.log', when = 'midnight', backupCount = 30)

如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

除非您指定了不同的编码,否则logging包文件处理程序会将您发送给它的任何Unicode对象编码为UTF-8。

使用io.open()再次将文件读取为UTF-8数据,您将再次获得unicode个对象,非常适合Jinja2:

import io

log = io.open('log.log', encoding='utf8')

您还可以为TimedRotatingFileHandler指定不同的编码,但UTF-8是一个很好的默认值。如果您想选择其他编码,请使用encoding关键字参数:

fileLogger = logging.handlers.TimedRotatingFileHandler(
    filename='log.log', when='midnight', backupCount=30,
    encoding='Latin1')

答案 1 :(得分:0)

我不熟悉flask,但是如果你可以把日志的内容作为字符串抓取。您可以将其编码为utf-8,如下所示:

string = string.encode('utf-8') # string is the log's contents, now in utf-8