mercredi 29 juin 2016

Why is my Logstash handler throwing a TypeError?

I'm creating a custom logger with the following code:

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

but when I use the logger returned from setup_custom_logger, I always get a TypeError.

I tried calling it with logger.info('hello') and with logger.info(b'hello'), but in both instances got:

--- 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'

It makes some sense that logging 'hello' would not work because 'hello' is, indeed, a str type.

However, b'hello' is a bytes-like object:

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

Why am I receiving this error? I'm using python-logstash 0.4.6 and Python 3.5.1.

Aucun commentaire:

Enregistrer un commentaire