What is the "right" way to use custom events and metrics for app insights in ASP.NET Core with dependency injection? Is there a way to inject TelemetryClient
?
Everything I can find instantiates the TelemetryClient
directly and TelemetryClient
doesn't implement an interface.
In the Azure Portal, navigate to the Application Insights resource, and click Log Analytics. Log queries help you to fully leverage the value of the data collected in Azure Monitor Logs. Query your custom events by entering “customEvents” in the prompt and click Run.
In Application Insights, a custom event is a data point that you can display in Metrics Explorer as an aggregated count and in Diagnostic Search as individual occurrences. (It isn't related to MVC or other framework "events.") Insert TrackEvent calls in your code to count various events.
In your function app, select Configuration under Settings, and then select Application settings. If you see a setting named APPINSIGHTS_INSTRUMENTATIONKEY , Application Insights integration is enabled for your function app running in Azure.
Application Insights sends telemetry from your web application to the Azure portal so that you can analyze the performance and usage of your application. The telemetry model is standardized, so it's possible to create platform and language-independent monitoring.
TelemetryClient is automatically injected to DI when you configure Application Insights using either .UseApplicationInsights()
or AddApplicationInsights()
methods. You can use constructor injection to get the TelemetryClient
instance as shown below.
public class HomeController : Controller
{
private TelemetryClient telemetry;
public HomeController(TelemetryClient telemetry)
{
this.telemetry = telemetry;
}
public IActionResult Index()
{
this.telemetry.TrackEvent("HomePageRequested");
return View();
}
}
https://github.com/Microsoft/ApplicationInsights-aspnetcore/wiki/Custom-Configuration#track-custom-traceeventmetric
i'm not sure you need to do dependency injection for that part.
other dependency injected stuff, like .UseApplicationInsights()
does the work to ensure application insights is configured, etc.
after that, code that would do custom events or metrics normally create a TelemetryClient
on demand, set shared context on the instance, and then write events/metrics through it, via the TrackEvent
, TrackMetric
, etc methods. Presuming AI is correctly configured in other places, those new telemetry client instances will have other shared/preconfigured/injected settings ready to go.
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