How do I enable Application Insights server telemetry on WebApi project that uses OWIN?

六眼飞鱼酱① 提交于 2019-12-03 11:25:18

问题


We are having a bunch of problems (read long response times) with a couple of projects in production and wanted to see exactly what was happening on the server. I then proceeded to add Application Insights to all of our projects by following this article. The problem is that both of our WebAPI projects are not sending server data to the Azure portal, while all other projects (MVC 5) are.

This is what is shown when I access the corresponding Application Insights blade on Azure:

I tried to disable and re-enable data collection in the Application Insights Status Monitor in our Azure VMs, restarted IIS a few times all while making requests to the API, to no avail. When I enable it on a MVC project, I can see the data almost instantly on the Azure portal when I open pages on the site.

When I saw that data was not being sent from our Azure VMs for these specific projects, I tried to setup the same collections in our dev environment, which is hosted in our own infrastructure, and the exact same situation repeated itself, ruling out the possibility that this is related to projects being hosted in Azure VMs.

I'm not exactly sure what is preventing these projects from sending data to Azure, but by taking a look at the working projects vs the non working ones, I think it might be somehow related to the fact that our WebAPI projects use the new OWIN pipeline while the MVC ones are standard MVC projects. I checked both the web.config file and the bin folder for both project types and they seem to be modified correctly by the Insights Monitor (I can see the same new dlls added to the bin folder and the same http module added to the web.config).

With that in mind, how do I enable server side telemetry using Application Insights for WebAPI projects that rely on the OWIN/Katana pipeline? What could I do to find out what exactly is causing the project to not send data to Azure in this case?


回答1:


AI uses httpmodule to collect information on begin request and send it on end request. As described here Owin/Katana uses middelwares to execute logic on a different stages. As most of AI auto collection logic is internal you cannot reuse it in your middleware. But you can instrument your code yourself. Create TelemetryClient from your code and start sending Request, Traces and Exceptions (like described here)




回答2:


This is an old question but it was still in the top 3 results on searches for "web api application insights owin". After lots of searching and not a lot of answers that didn't require us to write our own middleware or explictly instrumenting everything. We came across an extension package that made things super simple:

Here's the Github Repository for it and the associated NuGet Package

For those too lazy to look at the links, all that was needed to be added was:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseApplicationInsights();

        // rest of the config here...
    }
}

and add this to your ApplicationInsights.Config

<TelemetryInitializers>
    <!-- other initializers.. -->
    <Add Type="ApplicationInsights.OwinExtensions.OperationIdTelemetryInitializer, ApplicationInsights.OwinExtensions"/>
</TelemetryInitializers>



回答3:


Below is our implementation of a OWIN Middleware for Application Insights.

/// <summary>
/// Extensions to help adding middleware to the OWIN pipeline
/// </summary>
public static class OwinExtensions
{
    /// <summary>
    /// Add Application Insight Request Tracking to the OWIN pipeline
    /// </summary>
    /// <param name="app"><see cref="IAppBuilder"/></param>
    public static void UseApplicationInsights(this IAppBuilder app) => app.Use(typeof(ApplicationInsights));

}

/// <summary>
/// Allows for tracking requests via Application Insight
/// </summary>
public class ApplicationInsights : OwinMiddleware
{

    /// <summary>
    /// Allows for tracking requests via Application Insight
    /// </summary>
    /// <param name="next"><see cref="OwinMiddleware"/></param>
    public ApplicationInsights(OwinMiddleware next) : base(next)
    {
    }

    /// <summary>
    /// Tracks the request and sends telemetry to application insights
    /// </summary>
    /// <param name="context"><see cref="IOwinContext"/></param>
    /// <returns></returns>
    public override async Task Invoke(IOwinContext context)
    {
        // Start Time Tracking
        var sw = new Stopwatch();
        var startTime = DateTimeOffset.Now;
        sw.Start();

        await Next.Invoke(context);

        // Send tracking to AI on request completion
        sw.Stop();

        var request = new RequestTelemetry(
            name: context.Request.Path.Value,
            startTime: startTime,
            duration: sw.Elapsed,
            responseCode: context.Response.StatusCode.ToString(),
            success: context.Response.StatusCode >= 200 && context.Response.StatusCode < 300
            )
        {
            Url = context.Request.Uri,
            HttpMethod = context.Request.Method
        };

        var client = new TelemetryClient();
        client.TrackRequest(request);

    }
}


来源:https://stackoverflow.com/questions/29471811/how-do-i-enable-application-insights-server-telemetry-on-webapi-project-that-use

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!