【问题标题】:Get current InvocationId or operation_Id获取当前 InvocationId 或 operation_Id
【发布时间】:2021-02-07 18:50:54
【问题描述】:

有没有办法让custom_dimensions 有一个完整的输出日志?我在(Azure Functions 的)监视器选项卡中看到仅显示带有 operation_IdcustomDimensions['InvocationId'] 的消息。有没有办法将这两个参数添加到 opencensus 的所有日志消息中?

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

但是,另一种选择是加入 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]

【问题讨论】:

    标签: python azure-functions azure-monitoring python-logging opencensus


    【解决方案1】:

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

    【讨论】:

    • 如果可能的话,最好还能以某种方式获取操作 ID,因为这就是 Azure 函数监视器调用日志中显示的内容
    • 我已经有一段时间没有这样做了。我记得我搜索过它,但我找不到它。最终,MS 让您很难在 Azure Functions 中使用 python。对于某些功能,他们希望在他们的 .NET 和 C# 堆栈上推动您。当我可以构建自己的(docker)容器时,我有最好的 Python 体验 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多