没有项目描述
structlog-sentr的Python项目详细描述
结构日志哨兵
What | Where |
---|---|
Documentation | https://github.com/kiwicom/structlog-sentry |
Maintainer | @paveldedik |
基于https://gist.github.com/hynek/a1f3f92d57071ebc5b91
安装
使用pip:
安装包pip install structlog-sentry
用法
此模块旨在与structlog
一起使用,如下所示:
importsentry_sdkimportstructlogfromstructlog_sentryimportSentryProcessorsentry_sdk.init()# pass dsn in argument or via SENTRY_DSN env variablestructlog.configure(processors=[structlog.stdlib.add_log_level,# required before SentryProcessor()SentryProcessor(level=logging.ERROR),],logger_factory=...,wrapper_class=...,)log=structlog.get_logger()
不要忘记在之前添加structlog.stdlib.add_log_level
处理器
SentryProcessor
。SentryProcessor
类接受以下参数:
level
-此级别或更高级别的事件将报告给哨兵, 默认值是WARNING
active
-默认值为True
,设置为False
将禁用处理器
现在,异常被哨兵自动捕获,log.error()
:
try:1/0exceptZeroDivisionError:log.error()try:resp=requests.get(f"https://api.example.com/users/{user_id}/")resp.raise_for_status()exceptRequestException:log.error("request error",user_id=user_id)
没有sys.exc_info()
的记录呼叫也会被哨兵自动捕获:
log.info("info message",scope="accounts")log.warning("warning message",scope="invoices")log.error("error message",scope="products")
如果您不想将日志转发到岗哨,只需通过sentry_skip=True
logger方法的可选参数,如下所示:
log.error(sentry_skip=True)
岗哨标签
可以将structlog的部分或全部键/值对设置为哨兵event_dict
:
structlog.configure(processors=[structlog.stdlib.add_log_level,SentryProcessor(level=logging.ERROR,tag_keys=["city","timezone"]),],...)log.error("error message",city="Tehran",timezone="UTC+3:30",movie_title="Some title")
这将报告错误,哨兵事件将有city和timezone标记。
如果要将所有事件数据作为标记,请使用tag_keys="__all__"
创建SentryProcessor
。
structlog.configure(processors=[structlog.stdlib.add_log_level,SentryProcessor(level=logging.ERROR,tag_keys="__all__"),],...)
跳过多余的
默认情况下,SentryProcessor
将把event_dict
键/值对作为额外信息发送给哨兵。
有时您可能想跳过这一步,特别是在以哨兵标签的形式发送event_dict
时:
structlog.configure(processors=[structlog.stdlib.add_log_level,SentryProcessor(level=logging.ERROR,as_extra=False,tag_keys="__all__"),],...)
以json形式登录
如果要配置structlog
将输出格式化为json
(可能对于elk-stack)您必须使用SentryJsonProcessor
来防止
向哨兵报告的事件的副本。
fromstructlog_sentryimportSentryJsonProcessorstructlog.configure(processors=[structlog.stdlib.add_logger_name,# required before SentryJsonProcessor()structlog.stdlib.add_log_level,SentryJsonProcessor(level=logging.ERROR,tag_keys="__all__"),structlog.processors.JSONRenderer()],...)
这个处理器告诉sentry ignore记录器并手动捕获事件。
测试
运行所有测试:
tox
请注意,tox不知道何时更改requirements.txt
。
并且不会自动为测试运行安装新的依赖项。
运行pip install tox-battery
来安装一个修复这种愚蠢的插件。
贡献
创建一个合并请求并将其分配给@paveldedik以供审阅。