structlog与graylog GELF的集成,由graypy提供
项目描述
structlog与graylog GELF的集成,由graypy提供。
理由
Structlog 为从应用程序生成结构化日志消息提供了一个丰富的工具。 Graypy 提供了Python接口以在GELF格式中发出日志,该格式由graylog接受。实际上,structlog 预处理Python logging 模块的 _inputs_,而 graypy 处理输出(LogRecord 实例),并且两者都不期望对方存在。
graystruct 提供了一个小的集成层,由两个主要组件组成,这些组件与 structlog 和 graypy 结合使用。这些组件最小程度地改变了 structlog 和 graypy 在其接口点的行为,以便它们能够合作生成结构化日志。
示例
>>> import logging
>>> import structlog
>>> from graystruct.encoder import GELFEncoder
>>> from graystruct.handler import GELFHandler
>>> from graystruct.utils import add_app_context
>>> structlog.configure(
... logger_factory=structlog.stdlib.LoggerFactory(),
... processors=[
... # Prevent exception formatting if logging is not configured
... structlog.stdlib.filter_by_level,
... # Add file, line, function information of where log occurred
... add_app_context,
... # Format positional args to log as in stdlib
... structlog.stdlib.PositionalArgumentsFormatter(),
... # Add a timestamp to log message
... structlog.processors.TimeStamper(fmt='iso', utc=True),
... # Dump stack if ``stack_info=True`` passed to log
... structlog.processors.StackInfoRenderer(),
... # Format exception info is ``exc_info`` passed to log
... structlog.processors.format_exc_info,
... # Encode the message in GELF format (this must be the final processor)
... structlog.processors.GELFEncoder(),
... ],
... )
>>> std_logger = logging.getLogger()
>>> std_logger.setLevel(logging.WARNING)
>>> gelf_handler = GELFHandler('localhost', 12201)
>>> std_logger.addHandler(gelf_handler)
>>> logger = structlog.get_logger('some.package')
# Will transmit a GELF-encoded message
>>> logger.error('user.login', username='sjagoe')