0
votes

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.

2
Did you have App insight working before ?Vova Bilyachat
I see that your method has override can you please add to your question more information about it? Also is it azure function or web api or smth else?Vova Bilyachat
Do you have in your startup services.AddApplicationInsightsTelemetryWorkerService(); ?Vova Bilyachat
Ive updated my answerVova Bilyachat
@Rafael please try adding telemetry.Flush() after telemetry.TrackMetric(sample);(sample is here). And if you run the project in visual studio, you can also check in the visual studio output window to see if the metric is sent or not.Ivan Yang

2 Answers

1
votes

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):

enter image description here

1
votes

In my startup I do have

   services.AddApplicationInsightsTelemetry();

As you said you are using background worker

  1. Install package nuget Microsoft.ApplicationInsights.WorkerService
  2. in your startup:
  • 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

enter image description here

Then you click on event and you will go to next view

enter image description here

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"

enter image description here