python日志是为grafana loki准备的。
python-logging-loki的Python项目详细描述
python日志loki
loki的python日志处理程序。
https://grafana.com/loki
安装
pip install python-logging-loki
用法
importloggingimportlogging_lokihandler=logging_loki.LokiHandler(url="https://my-loki-instnace/api/prom/push",tags={"application":"my-app"},auth=("username","password"),)logger=logging.getLogger("my-logger")logger.addHandler(handler)logger.error("Something happened",extra={"tags":{"service":"my-service"}},)
上面的示例将与这些标签一起发送Something happened
消息:
- 处理程序中的默认标签
- 消息级别为
serverity
- 记录器的名称为
logger
- 来自
tags
项目的标签extra
dict
给定的示例是阻塞(即每个呼叫将等待消息发送)。
但是您可以使用内置的QueueHandler
和QueueListener
在单独的线程中发送消息。
importlogging.handlersimportlogging_lokifromqueueimportQueuequeue=Queue(-1)handler=logging.handlers.QueueHandler(queue)handler_loki=logging_loki.LokiHandler(url="https://my-loki-instnace/api/prom/push",tags={"application":"my-app"},auth=("username","password"),)logging.handlers.QueueListener(queue,handler_loki)logger=logging.getLogger("my-logger")logger.addHandler(handler)logger.error(...)
或者可以使用LokiQueueHandler
快捷方式,它将自动创建侦听器和处理程序。
importlogging.handlersimportlogging_lokifromqueueimportQueuehandler=logging_loki.LokiQueueHandler(Queue(-1),url="https://my-loki-instnace/api/prom/push",tags={"application":"my-app"},auth=("username","password"),)logger=logging.getLogger("my-logger")logger.addHandler(handler)logger.error(...)