Structlog库的处理器
structlog-extensions-nralbers的Python项目详细描述
Structlog扩展是一组structlog处理器和实用程序函数 向structlog添加新的日志记录选项。主要目的是提供转换现有structlog的工具 将输出记录到Elastic Common Schema json输出,因此用户可以轻松地将其应用程序输出插入集中式日志解决方案中,例如 ELK stack。
目前,扩展由一个CombinedLogParser(例如可以用来转换gunicorn访问日志) 输出到ECS字段),以及NestedDictJSONRenderer,它可用于转换CombinedLogParser的输出 转换成ECS json格式输出。
使用
CombinedLogParser
此处理器将把Apache组合日志格式的事件解析为 弹性公共模式字段。
示例
这是一个配置gunicorn以发出json日志的示例。
gunicorn.conf.py
importstructlogimportstructlog_extensions# --- Structlog logging initialisation codepre_chain=[# Add the log level and a timestamp to the event_dict if the log entry# is not from structlog.structlog.stdlib.add_log_level,structlog.stdlib.add_logger_name,structlog_extensions.processors.CombinedLogParser("gunicorn.access")]logconfig_dict={"version":1,"disable_existing_loggers":False,"formatters":{"json_formatter":{"()":structlog.stdlib.ProcessorFormatter,"processor":structlog.processors.JSONRenderer(),"foreign_pre_chain":pre_chain,}},"handlers":{"error_console":{"class":"logging.StreamHandler","formatter":"json_formatter",},"console":{"class":"logging.StreamHandler","formatter":"json_formatter",}},}
NestedDictJSONRenderer
在呈现 使用structlogjsonrenderer输出为JSON。例如,此处理器可以转换弹性公共模式名称空间 CombinedLogParser生成的keynames,将其转换为ECS指定的嵌套JSON格式。这个处理器必须是 链中的最终处理器,因为它将输出呈现为字符串,而不是传递事件字典。
示例
使用此日志初始化时:
# --- std logging initialisation code using structlog renderingimportstructlogimportstructlog_extensionspre_chain=[# Add the log level and a timestamp to the event_dict if the log entry# is not from structlog.structlog.stdlib.add_log_level,structlog.stdlib.add_logger_name,structlog_extensions.processors.CombinedLogParser("gunicorn.access")]logging.dict_config({"version":1,"disable_existing_loggers":False,"formatters":{"json_formatter":{"()":structlog.stdlib.ProcessorFormatter,"processor":structlog_extensions.processors.NestedDictJSONRenderer('.'),"foreign_pre_chain":pre_chain,}},"handlers":{"error_console":{"class":"logging.StreamHandler","formatter":"json_formatter",},"console":{"class":"logging.StreamHandler","formatter":"json_formatter",}},})These entries (produced by ^{tt7}$):
{'http.request.method':'get','http:.request.referrer':'http://www.example.com','http.version':'1.0'}`will be transformed into the following nested json structure:
{'http':{'version':'1.0','request':{'method':'get','referrer':'http://www.example.com'}}}
- 项目
标签: