Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Static Instance of TelemetryClient with Application Insights

Tags:

I have an ASP.NET MVC Website and I am implementing Application Insights. Right now, I log a Trace Event as follows:

private static TelemetryClient _APM; private static TelemetryClient APM {     get     {         if (_APM == null) { _APM = new TelemetryClient(); }         return _APM;     } }  public static void Trace(string Message) {     APM.TrackTrace(Message); } 

As you can see, this would maintain a single static instance of the TelemetryClient for all traces. Is this how we are supposed to use the client? Or are we supposed to create a new instance of TelemetryClient for each Log?

like image 607
William Avatar asked Jan 10 '16 18:01

William


2 Answers

According to the docs you should:

... use an instance of TelemetryClient for each module of your app. For instance, you may have one TelemetryClient in your web service to report incoming http requests, and another in a middleware class to report business logic events.

It is probably expensive to create a new telemetry client for every log, so depending on the structure of your application you are probably right to use the singleton pattern you have described in your post.

like image 110
darth_phoenixx Avatar answered Sep 24 '22 18:09

darth_phoenixx


The full quote that darth_phoenixx referenced actually reads:

TelemetryClient is thread-safe.

For ASP.NET and Java projects, incoming HTTP Requests are automatically captured. You might want to create additional instances of TelemetryClient for other module of your app. For instance, you may have one TelemetryClient instance in your middleware class to report business logic events. You can set properties such as UserId and DeviceId to identify the machine. This information is attached to all events that the instance sends.

TelemetryClient.Context.User.Id = "..."; TelemetryClient.Context.Device.Id = "..."; 

That last bit is extremely important. If you are writing something like a web application where the UserId might change, you should probably reuse an instance of the telemetry client for each scope in which these values would all be the same (like each Request), but not as a static/singleton instance.

Update

In ASP.NET Core, Application Insights makes heavy use of dependency injection and registers TelemetryClient as a singleton!

This means you should avoid setting variables on the client context which you don't want to be used throughout the application, and instead leverage Telemetry Initializers to set things like the user ID on each telemetry object.

like image 43
StriplingWarrior Avatar answered Sep 20 '22 18:09

StriplingWarrior