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

Why is my Logstash handler throwing a TypeError?

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

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.

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