I'm trying to send custom metrics to an App Service in Azure Portal given an instrumentation key. I have the following code running in .NET Core as part of a Background service:
public override async Task StartAsync(CancellationToken stoppingToken)
{
try
{
TelemetryClient telemetry = new TelemetryClient();
telemetry.TrackEvent("new event");
var sample = new MetricTelemetry();
sample.Name = "metric name";
sample.Value = 42.3;
telemetry.TrackMetric(sample);
telemetry.Flush();
}
catch (Exception e)
{
_logger.LogError($"{e.Message} {e.StackTrace}");
}
}
This sample code comes from: https://docs.microsoft.com/en-us/azure/azure-monitor/app/api-custom-events-metrics
However I'm not sure if these metrics are even reaching the Azure instance or where to look for them. I went to Application Insights > MyInstance > Logs and found a table there named 'customEvents'. However I can't query over it. On the Metrics tabs I only get the default metrics namespace which shows the default metrics available in Azure, but not any new custom metrics.
In my startup I do have
services.AddApplicationInsightsTelemetry();
As you said you are using background worker
Microsoft.ApplicationInsights.WorkerService
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args).ConfigureServices((hostContext, services) => {..... services.AddApplicationInsightsTelemetryWorkerService(); });
Simple way to find would be to go to app insight transaction search and search for event name
Then you click on event and you will go to next view
Thats how I would check if you events are actually logged.
Also I just run queries
customMetrics
| where name == "metric name"
customEvents
| where name == "Error.PageNotFound"
I think the issue is that you create a new telemetry client
by using this line of code: TelemetryClient telemetry = new TelemetryClient();
, but the new telemetry client
does not configure a InstrumentationKey
. Then the custom events
/ custom metrics
are not sent by using telemetry.TrackEvent
/ telemetry.TrackMetric
methods.
You should change it like below in Worker.cs
:
namespace WorkerService3
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
//define a telemetry client here, and use it in your following code
private TelemetryClient telemetry;
public Worker(ILogger<Worker> logger, TelemetryClient tc)
{
_logger = logger;
telemetry = tc;
}
public override async Task StartAsync(CancellationToken stoppingToken)
{
try
{
//do not create a another telemetry client, use the one defined in class-level.
//TelemetryClient telemetry = new TelemetryClient();
telemetry.TrackTrace("StartAsync: new message");
telemetry.TrackEvent("StartAsync: new event");
var sample = new MetricTelemetry();
sample.Name = "StartAsync metric name";
sample.Value = 11.55;
telemetry.TrackMetric(sample);
telemetry.Flush();
}
catch (Exception e)
{
_logger.LogError($"{e.Message} {e.StackTrace}");
}
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
//other code
}
}
}
And this is my Program.cs
:
namespace WorkerService3
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
services.AddApplicationInsightsTelemetryWorkerService();
});
}
}
This is my appsettings.json:
{
"ApplicationInsights": {
"InstrumentationKey": "your application insights InstrumentationKey"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
After the code is executed, wait for a few minutes, I can search custom metrics / custom events in azure portal -> my application insights -> Logs(for custom events, query the customEvents
table):
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.