Python应用程序的Azure Application Insights日志记录-明确设置例外属性

问题描述

我试图将运行在 Azure App服务中的 Python应用程序中的异常发送到指定的 Azure Application Insights 实例。我为此使用OpenCensus python库。 基本日志记录和异常已成功到达App Insight。

除此之外,我想知道是否有一种方法可以配置Exception属性,例如:problemId或任何其他属性,以显式反映特定的值以更容易地发出警报(例如发送电子邮件到基于问题ID的特定组)。

任何建议/指针都将非常有帮助

解决方法

您可以使用custom_dimensions字段在extra关键字参数中向日志消息添加自定义属性(不仅是异常,还包括所有其他日志类型,例如跟踪,事件等)。这些属性在Azure Monitor的customDimensions中显示为键值对。然后,您可以基于此查询,查看或配置警报。

要使用此功能,您需要将字典传递到custom_dimensions字段。如果您传递任何其他类型的参数,记录器将忽略它们。

注意:OpenCensus Python不会自动跟踪和发送异常遥测。它们是通过Python日志库使用异常通过AzureLogHandler发送的。您可以像常规日志记录一样添加自定义属性。

import logging

from opencensus.ext.azure.log_exporter import AzureLogHandler

logger = logging.getLogger(__name__)
# TODO: replace the all-zero GUID with your instrumentation key.
logger.addHandler(AzureLogHandler(
    connection_string='InstrumentationKey=00000000-0000-0000-0000-000000000000')
)

properties = {'custom_dimensions': {'key_1': 'value_1','key_2': 'value_2'}}

# Use properties in exception logs
try:
    result = 1 / 0  # generate a ZeroDivisionError
except Exception:
    logger.exception('Captured an exception.',extra=properties)

您可以在Azure门户中查看如下所示的customDimentions(仅作为示例,并非根据上述代码实际):

![](https://camerondwyer.files.wordpress.com/2020/05/app-insights-kusto-custom-properties-01-trace-event.png?w=1024)

您可以在Kusto查询中看到如下内容:

enter image description here

您可以查询这些内容并根据其配置警报(下图显示traces,例外情况是exceptions table

enter image description here