获取当前的InvocationId或operation_Id

问题描述

是否可以使用custom_dimensions获得一个完整的输出日志?我在(Azure Functions)的“监视”选项卡中看到,仅显示带有operation_IdcustomDimensions['InvocationId']的消息。是否可以通过opencensus将这两个参数添加到所有日志消息中?

我知道您可以use a second logger。但这仅有助于调试。为了在生产环境中运行Azure功能,我需要查看两个流。这是可能的,但是效率低下并且令人沮丧,因为信息被断开并且无法汇总。

不过,另一种选择是在Azure Monitor端加入流。但是除非知道当前的InvocationIdoperation_Id,否则我无法这样做。因此,我的问题是是否可以将这两个ID中的任何一个添加到当前日志消息中

我的最小示例__init__.py看起来像这样:

from opencensus.ext.azure.log_exporter import AzureLogHandler
import logging.config
import yaml

import azure.functions as func

# Load logging configuration
with open("logging.yaml",'rt') as f: # for local debugging add the console handler to the output
    config_data = yaml.safe_load(f.read())
    logging.config.dictConfig(config_data)

def main(mytimer: func.TimerRequest) -> None:
    try: 
        someID = 14
        logging.debug('debug message',extra = {'custom_dimensions': {'ID': someID}})
        logging.info('info message',extra = {'custom_dimensions': {'ID': someID}})
        logging.warning('warn message',extra = {'custom_dimensions': {'ID': someID}})
        logging.error('error message',extra = {'custom_dimensions': {'ID': someID}})
        logging.critical('critical message',extra = {'custom_dimensions': {'ID': someID}})
    except Exception as e:
        logging.error("Main program Failed with error: " + str(e))

我希望将日志记录配置保留在logging.yaml中:

version: 1
formatters:
  simple:
    format: '%(asctime)s | %(levelname)-8s | %(module)s:%(funcName)s:%(lineno)d | %(message)s'
handlers:
  azure:
    class: opencensus.ext.azure.log_exporter.AzureLogHandler
    level: DEBUG
    formatter: simple
    instrumentation_key: 'your-key'
loggers:
  simpleExample:
    level: DEBUG
    handlers: [azure]
    propagate: no
root:
  level: INFO
  handlers: [azure]

解决方法

找到right part in the documentation之后,它非常简单:

def main(mytimer: func.TimerRequest,context: func.Context) -> None:
    try: 
        invocation_id = context.invocation_id
        # Function continues here. 

    except Exception as e:
        logging.error("Main program failed with error: " + str(e))

请注意,只有将func.Context分配给context时,此解决方案才有效。使用context以外的其他名称对我来说会导致错误-.-