为什么我的Logstash处理程序抛出TypeError?

时间:2016-06-25 20:40:42

标签: python python-3.x logging logstash bytestream

我使用以下代码创建自定义记录器:

import logging
import logstash

from socket import gethostname

class CustomLogger(logging.Logger):
    def _log(self, level, msg, args, exc_info=None, extra=None):
        if extra is None:
            extra = { 'hostname' : gethostname() }
        super(CustomLogger, self)._log(level, msg, args, exc_info, extra)

def setup_custom_logger(host, port):
    # add hostname to the formatter.
    logging.setLoggerClass(CustomLogger)

    formatter = logging.Formatter(fmt='%(hostname)s - %(asctime)s - %(levelname)s - %(module)s - %(message)s')

    logstash_handler = logstash.LogstashHandler(host, port, version=2)
    logstash_handler.setLevel(logging.DEBUG)
    logstash_handler.setFormatter(formatter)

    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(logstash_handler)

    return logger

但是当我使用从setup_custom_logger返回的记录器时,我总是得到TypeError

我尝试使用logger.info('hello')logger.info(b'hello')调用它,但在两个实例中都得到了:

--- Logging error ---
Traceback (most recent call last):
  File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/logging/handlers.py", line 620, in emit
    self.send(s)
  File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/logging/handlers.py", line 678, in send
    self.sock.sendto(s, self.address)
TypeError: a bytes-like object is required, not 'str'

记录'hello'无法正常运行,因为'hello'确实是str类型。

但是,b'hello'是一个类似字节的对象:

>>> type(b'hello')
<class 'bytes'>

为什么我收到此错误?我使用的是python-logstash 0.4.6和Python 3.5.1。

1 个答案:

答案 0 :(得分:0)

问题在于格式化程序。我删除了将格式化程序添加到logstash_handler对象的行,并根据配置成功登录到logstash。