获取当前调用Id或操作\u Id

2024-05-29 11:51:20 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法用custom_dimensions创建一个完整的输出日志?我在(Azure函数的)monitor选项卡中看到,只显示带有operation_IdcustomDimensions['InvocationId']的消息。有没有办法将这两个参数添加到opencensus的所有日志消息中

我知道你可以。但这只对调试有帮助。为了在生产环境中运行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]

Tags: importidconfig消息yamlmessageloggingcustom
1条回答
网友
1楼 · 发布于 2024-05-29 11:51:20

在找到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以外的任何其他名称都会导致me-的错误

相关问题 更多 >

    热门问题