0

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

我知道您可以使用第二个记录器。但这仅有助于调试。为了在生产环境中运行 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]
4

1 回答 1

2

在文档中找到正确的部分后,它非常容易:

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导致我出错-.-

于 2020-10-25T11:29:59.367 回答