Joo*_*ost 5 azure-application-insights azure-functions
我有一个 Azure 函数 (v2),其中数据通过 HTTP 正文作为 JSON 传入。我想使用标准的Trace和Request事件在 Application Insights 中记录其中的一些 JSON 数据。
到目前为止我尝试过的:
ITelemetryInitializer解析正文并将属性添加到ISupportProperties.Properties. 但这有两个缺点:每个请求都会多次读取和解析主体(一次在我的函数中,在遥测初始化程序中多次),有时访问主体会抛出异常,因为它已被处理(可能它会消失)函数调用结束时的范围)。TelemetryClient在我的函数中使用一个。但是这个客户端似乎没有合适的属性来设置:
TelemetryClient.Context.GlobalProperties 用于全局属性,而不是请求范围的属性;TelemetryClient.Context.Properties已过时,我不知道如何在ISupportProperties.Properties那里使用推荐的替代品。理想情况下,我想使用在我的函数中解析的数据,并使用该数据来初始化遥测数据。
小智 6
您可以通过添加标签更新请求遥测性质Activity.Current一样 Activity.Current?.AddTag("my-prop", ExtractPropFromRequest()); 没有任何额外的变化,这些标签将出现在请求。不幸的是,您不会将它们印在痕迹上。
您还可以在函数中解析一次请求正文并将其存储在 AsyncLocal 中。然后在 TelemetryInitializer 中访问这个 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;
// ...
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1265 次 |
| 最近记录: |