gpt4 book ai didi

python - 在 python Azure Functions 中自定义日志格式

转载 作者:行者123 更新时间:2023-12-03 03:45:57 27 4
gpt4 key购买 nike

我正在编写许多 Python Azure 函数。我希望日志中的每一行都以 context 中的 invocation-id 为前缀,以便轻松隔离和关联日志。

我知道有multiple ways为普通/独立的 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

我见过some docs在 Azure 上,似乎没用。

最佳答案

您可以使用 LoggerAdapter 来执行此操作,如以下可运行程序所示:

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,那么您可以按照文档hereLogger进行子类化。或使用记录的Filter here 。但在后一种情况下,您仍然必须将过滤器附加到所有感兴趣的记录器(或处理程序,这会更容易)。

关于python - 在 python Azure Functions 中自定义日志格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69212945/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com