Search code examples
c#azure-application-insights.net-standardclass-library

How to use application insights in .net standard library?


I have used application insights in web api. It works well. Currently, our controller need call a class library (referred by nuget package). I need to use application insight in class library. There is no exception but nothing logged in Application insights. I write the code as following. Our TelemetryConfiguration have initialized in controller already.

var telemetryClient = new TelemetryClient();
var customEvent = new Microsoft.ApplicationInsights.DataContracts.EventTelemetry
{
    Name = "helloworld",
};
// customEvent.Metrics.Add({ "latency", 42});
telemetryClient.TrackEvent(customEvent);

What should I do to make the application insights work?


Solution

  • Normally the following steps are enough to log to App Insights:

    1- In your WebApi startup class and your library project add App Insights assembly thru nuget.

    Microsoft.ApplicationInsights
    

    2- Register App Insights in your startup class:

    services.AddApplicationInsightsTelemetry(Configuration);
    

    3- Setup your instrumentation key in appsettings.json:

    "ApplicationInsights": {
      "InstrumentationKey": "<Your instrumentation key here>"
    }
    

    4- In any class you need, inject a TelemetryClient and use it.

    using Microsoft.ApplicationInsights
    
    namespace MyNamesPace
    {
        public class MyClass
        {
            private readonly TelemetryClient _telemetryClient;
    
            public MyClass(TelemetryClient telemetryClient)
            {
                _telemetryClient= telemetryClient;
            }
    
            public myClassMethod()
            {
                // Use your _telemetryClient instance
                _telemetryClient.TrackEvent("Your Telemetry Event");
            }
        }
    }
    

    4- In your controller inject your class

    namespace MyApiNamesPace
    {
        public class MyController : ControllerBase
        {
            private readonly IMyClass _myClass;
    
            public MyClass(IMyClass myClass)
            {
                _myClass = myClass;
            }
    
            public IActionResult myAction()
            {
                _myClass.MyClassMethod();
            }
        }
    }
    

    5- Don't forget to register your class in your DI container, in startup class:

    services.AddScoped<IMyClass, MyClass>();
    

    Happy programming!!