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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With