代码之家  ›  专栏  ›  技术社区  ›  Andrew Grant

如何在python日志中使用utf-8?

  •  36
  • Andrew Grant  · 技术社区  · 17 年前

    我正在尝试使用python的日志包将一个utf-8编码的字符串记录到一个文件中。作为一个玩具例子:

    import logging
    
    def logging_test():
        handler = logging.FileHandler("/home/ted/logfile.txt", "w",
                                      encoding = "UTF-8")
        formatter = logging.Formatter("%(message)s")
        handler.setFormatter(formatter)
        root_logger = logging.getLogger()
        root_logger.addHandler(handler)
        root_logger.setLevel(logging.INFO)
    
        # This is an o with a hat on it.
        byte_string = '\xc3\xb4'
        unicode_string = unicode("\xc3\xb4", "utf-8")
    
        print "printed unicode object: %s" % unicode_string
    
        # Explode
        root_logger.info(unicode_string)
    
    if __name__ == "__main__":
        logging_test()
    

    这会在logging.info()调用中以unicodedecodeerror爆炸。

    在较低的级别上,python的日志包使用codecs包打开日志文件,并将“utf-8”参数作为编码传递。这一切都很好,但它试图将字节字符串写入文件,而不是Unicode对象,后者会爆炸。基本上,python是这样做的:

    file_handler.write(unicode_string.encode("UTF-8"))
    

    当它应该这样做时:

    file_handler.write(unicode_string)
    

    这是巨蟒身上的虫子,还是我在吃疯狂的药丸?fwiw,这是一个stock python 2.6安装。

    4 回复  |  直到 12 年前
        1
  •  13
  •   Vinay Sajip    17 年前

    检查您是否有最新的python 2.6——自从2.6出现以来,发现并修复了一些unicode错误。例如,在我的UbuntuJaunty系统上,我运行了复制和粘贴的脚本,只从日志文件名中删除了“/home/ted/”前缀。结果(从终端窗口复制和粘贴):

    vinay@eta-jaunty:~/projects/scratch$ python --version
    Python 2.6.2
    vinay@eta-jaunty:~/projects/scratch$ python utest.py 
    printed unicode object: ô
    vinay@eta-jaunty:~/projects/scratch$ cat logfile.txt 
    ô
    vinay@eta-jaunty:~/projects/scratch$ 
    

    在Windows框中:

    C:\temp>python --version
    Python 2.6.2
    
    C:\temp>python utest.py
    printed unicode object: ô
    

    文件内容:

    alt text

    这也可以解释为什么莱纳特·雷杰布罗也不能复制它。

        2
  •  24
  •   warvariuc    12 年前

    具有类似代码:

    raise Exception(u'щ')
    

    引起:

      File "/usr/lib/python2.7/logging/__init__.py", line 467, in format
        s = self._fmt % record.__dict__
    UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)
    

    这是因为格式字符串是字节字符串,而某些格式字符串参数是具有非ASCII字符的Unicode字符串:

    >>> "%(message)s" % {'message': Exception(u'\u0449')}
    *** UnicodeEncodeError: 'ascii' codec can't encode character u'\u0449' in position 0: ordinal not in range(128)
    

    将格式字符串设置为Unicode可以解决以下问题:

    >>> u"%(message)s" % {'message': Exception(u'\u0449')}
    u'\u0449'
    

    因此,在日志配置中,将所有格式字符串设置为Unicode:

    'formatters': {
        'simple': {
            'format': u'%(asctime)-s %(levelname)s [%(name)s]: %(message)s',
            'datefmt': '%Y-%m-%d %H:%M:%S',
        },
     ...
    

    修补默认值 logging 要使用Unicode格式字符串的格式化程序:

    logging._defaultFormatter = logging.Formatter(u"%(message)s")
    
        3
  •  1
  •   John    17 年前

    试试这个:

    import logging
    
    def logging_test():
        log = open("./logfile.txt", "w")
        handler = logging.StreamHandler(log)
        formatter = logging.Formatter("%(message)s")
        handler.setFormatter(formatter)
        root_logger = logging.getLogger()
        root_logger.addHandler(handler)
        root_logger.setLevel(logging.INFO)
    
        # This is an o with a hat on it.
        byte_string = '\xc3\xb4'
        unicode_string = unicode("\xc3\xb4", "utf-8")
    
        print "printed unicode object: %s" % unicode_string
    
        # Explode
        root_logger.info(unicode_string.encode("utf8", "replace"))
    
    
    if __name__ == "__main__":
        logging_test()
    

    值得一提的是,我希望必须使用codecs.open以utf-8编码打开文件,但这是默认值,或者这里正在发生其他事情,因为它的工作方式是这样的。

        4
  •  1
  •   Epu    13 年前

    如果我正确理解了您的问题,那么当您这样做时,您的系统也会出现同样的问题:

    str(u'ô')
    

    我想,在启用区域设置感知之前,在Unix上对区域设置编码的自动编码将无法工作。 if 分支在 setencoding 在您的 site 模块VIA locale . 此文件通常位于 /usr/lib/python2.x 无论如何,它值得检查。Afaik,现场感知 集编码 默认情况下是禁用的(对于我的python 2.6安装是这样)。

    选择包括:

    • 让系统找出正确的方法将Unicode字符串编码为字节或在代码中进行编码(某些特定于站点的配置 site.py 是需要的)
    • 在代码中对Unicode字符串进行编码并只输出字节

    也见 The Illusive setdefaultencoding 由伊恩比金和相关链接。