首页 > 解决方案 > 在 python Azure Functions 中自定义日志格式

问题描述

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

我知道对于普通/独立的 python 应用程序有多种方法可以做到这一点。在这里,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 上看过一些文档,似乎没用。

标签: pythonazureloggingazure-functions

解决方案


您可以使用 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使用此处记录Filtera 。但在后一种情况下,您仍然必须将过滤器附加到所有感兴趣的记录器(或处理程序,这会更容易)。


推荐阅读