我正在尝试设置 structlog 并设置日志级别。我的代码如下所示:
import structlog
import logging
filepath=open("out.log",'a')
logging.basicConfig(
level=logging.INFO
)
structlog.configure(
processors=[structlog.stdlib.filter_by_level],
wrapper_class=structlog.BoundLogger,
context_class=dict,
logger_factory=structlog.PrintLoggerFactory(filepath),
)
logger = structlog.getLogger()
logger.info('test')
这失败了:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.8/site-packages/structlog/_base.py", line 189, in _proxy_to_logger
args, kw = self._process_event(method_name, event, event_kw)
File "/usr/local/lib/python3.8/site-packages/structlog/_base.py", line 149, in _process_event
event_dict = proc(self._logger, method_name, event_dict)
File "/usr/local/lib/python3.8/site-packages/structlog/stdlib.py", line 381, in filter_by_level
if logger.isEnabledFor(_NAME_TO_LEVEL[name]):
AttributeError: 'PrintLogger' object has no attribute 'isEnabledFor'
好的,当然。我不应该将 PrintLogger 与 stdlib 处理器一起使用。但是我想按日志级别进行过滤(因为这就是日志通常的工作方式,嗯?)那我该怎么做呢?我假设我需要使用其他一些记录器工厂,但是哪一个?当然 structlog.stdlib.LoggerFactory 可以工作,但它不会重定向到文件。
所以我说:好的,我将创建自己的过滤器:
def my_filter_by_level(logger, name, event_dict):
if True:
return event_dict
else:
raise DropEvent
...
processors=[my_filter_by_level],
当我尝试使用记录器时,我得到:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.8/site-packages/structlog/_base.py", line 190, in _proxy_to_logger
return getattr(self._logger, method_name)(*args, **kw)
TypeError: msg() got an unexpected keyword argument 'organization'
这是来自
logger = logger.bind(**{"organization": "blah"})
但为什么?我的处理器有什么问题?