我有一个 Azure 函数 (v2),其中数据通过 HTTP 主体以 JSON 形式传入。我想使用标准在 Application Insights 中记录一些 JSON 数据Trace and Request events.
到目前为止我尝试过的:
- 使用自定义
ITelemetryInitializer
它解析主体并添加属性ISupportProperties.Properties
。但这有两个缺点:每个请求都会多次读取和解析主体(在我的函数中一次,在遥测初始化程序中多次),有时访问主体会抛出异常,因为它已被处理(可能它会出去)函数调用结束时的范围)。
- Use an
TelemetryClient
inside my Function. But this client doesn't seem to have an appropriate property to set:
-
TelemetryClient.Context.GlobalProperties
适用于全局属性,而不是请求范围的属性;
-
TelemetryClient.Context.Properties
已过时,我不知道如何使用推荐的替代品ISupportProperties.Properties
there.
理想情况下,我想使用在函数内部解析的数据,并使用该数据来初始化遥测数据。
您可以通过添加标签来更新请求遥测属性Activity.Current
like Activity.Current?.AddTag("my-prop", ExtractPropFromRequest());
无需任何其他更改,这些标签将出现在请求中。不幸的是,你不会把它们印在痕迹上。
您还可以在函数中解析一次请求正文并将其存储在 AsyncLocal 中。然后在ITelemetryInitializer中访问这个AsyncLocal
public class AsyncLocalPropertyTelemetryInitializer : ITelemetryInitializer
{
public void Initialize(ITelemetry telemetry)
{
if (telemetry is ISupportProperties propTelemetry &&
Function1.AdditionalContext.Value != null) // you may find a better way to make it work with DI
{
propTelemetry.Properties["my-prop"] = Function1.AdditionalContext.Value;
}
}
}
public static class Function
{
internal static readonly AsyncLocal<string> AdditionalContext = new AsyncLocal<string>();
[FunctionName("Function1")]
public static async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log)
{
AdditionalContext.Value = "something important"; // read the body here
log.LogInformation("C# HTTP trigger function processed a request.")
AdditionalContext.Value = null;
// ...
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)