我正在使用以下代码创建一个自定义记录器:
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。