python - 在 python Azure Functions 中自定义日志格式
问题描述
我正在编写许多 Python Azure 函数。我希望日志中的每一行都以invocation-id
from为前缀,context
以便轻松地隔离和关联日志。
我知道对于普通/独立的 python 应用程序有多种方法可以做到这一点。在这里,Azure Function 运行时提供了一个调用我的代码的环境。我不想/不喜欢:
- 弄乱由 Azure Function 运行时注册的现有处理程序/格式化程序或
- 编写我自己的处理程序/格式化程序
(因为默认情况下注册的任何内容都会将日志发送到 Azure Log Analytics 工作区并为我的仪表板等提供动力)
例如以下代码:
import logging
from azure import functions as func
def main(msg: func.QueueMessage, ctx: func.Context) -> None:
logging.info('entry')
logging.info('invocation id of this run: %s', ctx.invocation_id)
logging.debug('doing something...')
logging.info('exit with success')
将产生如下日志:
entry
invocation id of this run: 111-222-33-4444
doing something...
exit with success
我想要的是:
(111-222-33-4444) entry
(111-222-33-4444) invocation id of this run: 111-222-33-4444
(111-222-33-4444) doing something...
(111-222-33-4444) exit with success
我在 Azure 上看过一些文档,似乎没用。
解决方案
您可以使用 aLoggerAdapter
来执行此操作,如以下可运行程序所示:
import logging
class Adapter(logging.LoggerAdapter):
def process(self, msg, kwargs):
return '(%s) %s' % (self.extra['context'], msg), kwargs
def main(msg, ctx):
logger = Adapter(logging.getLogger(), {'context': ctx})
logger.info('entry')
logger.info('invocation id of this run: %s', ctx)
logger.debug('doing something ...')
logger.info('exit with success')
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG, format='%(message)s')
main('hello', '111-222-33-4444')
显然我已经删除了 Azure 引用,以便我可以在本地运行它,但你应该明白要点。前面的脚本打印
(111-222-33-4444) entry
(111-222-33-4444) invocation id of this run: 111-222-33-4444
(111-222-33-4444) doing something ...
(111-222-33-4444) exit with success
更新:如果您不想/不能使用LoggerAdapter
,那么您可以按照此处记录的方式进行子类化Logger
或使用此处记录的Filter
a 。但在后一种情况下,您仍然必须将过滤器附加到所有感兴趣的记录器(或处理程序,这会更容易)。
推荐阅读
- python - Scikit-Learn 包装器和 RandomizedSearchCV:RuntimeError
- javascript - 使用正则表达式验证电子邮件,其中域部分中的扩展数可能会有所不同
- android - 5分钟后自动注销应用程序在xamarin表单中处于终止状态或后台状态?
- reactjs - Suspense 数据获取中的 UseRef
- pandas - 如何将数据框文本列拆分为布尔列
- excel - 尝试使用 VBA 对一行中的值求和,但无法解决代码中的错误
- javascript - 如何修复 `data-rbd-draggable-context-id` 不匹配。服务器:“1”客户端:“0”,带有 react-beautiful-dnd 和 next.js
- django - 复选框 Django ModelForm 列表
- java - MySQL 不会显示数据库中的用户,即使它们存在
- javascript - 问题接收访问令牌