簡體   English   中英

Web API + Azure App Insights將數據從ActionFilter傳遞到ITelemetryProcessor

[英]Web API + Azure App Insights pass the data from ActionFilter to ITelemetryProcessor

我想自定義我的Application Insights日志記錄行為。 所以我想在ActionFilter中設置某種標志,然后在ITelemetryProcessor中讀取該標志。

public class MyCustomFilterAttribute: ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext filterContext)
    {
        //perform some logic and set the flag here
    }
}

接着

public class TelemetryFilter : ITelemetryProcessor
{
    public void Process(ITelemetry item)
    {
        var request = item as RequestTelemetry;
        //read the flag here and terminate processing
    }
}

那可能嗎 ? 這兩種類型之間是否共享某種TempData? 我想避免諸如設置臨時標頭之類的黑客行為。 提前致謝。

我不確定這是否有用。 但我希望會。

使用Activity.Current

    public void Initialize(ITelemetry telemetry)
    {
        Activity current = Activity.Current;

        if (current == null)
        {
            current = (Activity)HttpContext.Current?.Items["__AspnetActivity__"];
//put your code here
        }
}

請參閱本SO

編寫一個TelemetryInitializer,您可以在其中訪問HttpContext。

// TelemetryInitializer

public void Initialize(ITelemetry telemetry)
    {
     var ctx = HttpContext.Current; // Telemetry Initialzer runs in same thread as the request.
     var request = item as RequestTelemetry;
     req.Properties.Add("MyActionFilter", "MyActionFilterValue")
     ...
    }

// TelemetryProcessor

public void Process(ITelemetry item)
    {
        var request = item as RequestTelemetry;
        //read the flag here and terminate processing
        if(req.Properties["MyActionFilter"] == "somthing")
        {
        ...
        }
    }

https://docs.microsoft.com/en-us/azure/application-insights/app-insights-api-filtering-sampling#itelemetryprocessor-and-itelemetryinitializer

對於Asp.Net Core,將IHttpContextAccessor注入TelemetryInitializer構造函數可以為您提供上下文,如下所示: https : //github.com/Microsoft/ApplicationInsights-aspnetcore/blob/develop/src/Microsoft.ApplicationInsights.AspNetCore/TelemetryInitializers/TelemetryInitializerBase的.cs

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM