【问题标题】:Python3 compress logger module logs on the flyPython3即时压缩记录器模块日志
【发布时间】:2014-10-09 12:59:03
【问题描述】:

我找不到压缩使用logger 模块编写的日志的方法。

例如:

import logging
import gzip

logger = logging.getLogger('')
z_file = gzip.open('out.log.gz', mode='wb')
logger.addHandler(logging.StreamHandler(z_file))
logger.warning("test".encode("UTF-8"))

codecs.opengzip.open都给我

--- Logging error ---
Traceback (most recent call last):
  File "/usr/lib/python3.4/logging/__init__.py", line 966, in emit
    stream.write(msg)
  File "/usr/lib/python3.4/gzip.py", line 343, in write
    self.crc = zlib.crc32(data, self.crc) & 0xffffffff
TypeError: 'str' does not support the buffer interface

当我尝试使用他们的处理程序时。我做错了什么?

不包含logger模块的相关问题:Writing append only gzipped log files in Python

【问题讨论】:

  • 请创建最短的完整程序来演示您看到的错误。将该简短而完整的程序复制粘贴到您的问题中。
  • @Robᵩ,完成。更新了问题。

标签: python logging python-3.x compression


【解决方案1】:

encoding 指定为gzip.open。您应该使用显式文本模式 (wt) 来指定编码。只需将字符串传递给日志记录方法。

import logging
import gzip

logger = logging.getLogger('')
z_file = gzip.open('out.log.gz', mode='wt', encoding='utf-8')
logger.addHandler(logging.StreamHandler(z_file))
logger.warning("test")

【讨论】:

  • 看起来第一个版本至少可以移到下面。
  • @int_ua,我通常保持原样。否则,它可能会混淆未来的读者。当前布局(?)与问题布局匹配。
  • 我已经编辑了这个问题。我认为它会加快那些寻找答案的人。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-04
  • 1970-01-01
  • 2012-01-18
相关资源
最近更新 更多