How to enable dotnet metric collection

28 Views Asked by At

The example that is being applied is at https://learn.microsoft.com/en-us/dotnet/core/diagnostics/metrics-collection However, the metrics is not visible under dotnet counters.

How can the metrics be seen?

When the program is compiled

using System;
using System.Collections.Generic;
using System.Diagnostics.Metrics;
using System.Threading;

namespace ConsoleApp7
{
    internal   class Program
    {
        static  void Main(string[] args)
        {
            Meter s_meter = new("HatCo.HatStore", "1.0.0");
             Counter<int> s_hatsSold = s_meter.CreateCounter<int>("hats-sold");


            using MeterListener meterListener = new();
                meterListener.InstrumentPublished = (instrument, listener) =>
                {
                    if (instrument.Meter.Name is "HatCo.HatStore")
                    {
                        listener.EnableMeasurementEvents(instrument);
                    }
                };

                meterListener.SetMeasurementEventCallback<int>(OnMeasurementRecorded);
                // Start the meterListener, enabling InstrumentPublished callbacks.
                meterListener.Start();

                var rand = Random.Shared;
                Console.WriteLine("Press any key to exit");
                while (!Console.KeyAvailable)
                {
                    //// Simulate hat selling transactions.
                    Thread.Sleep(rand.Next(100, 2500));
                    s_hatsSold.Add(rand.Next(0, 1000));
                }
           

            static void OnMeasurementRecorded<T>(
                Instrument instrument,
                T measurement,
                ReadOnlySpan<KeyValuePair<string, object?>> tags,
                object? state)
            {
                Console.WriteLine($"{instrument.Name} recorded measurement {measurement}");
            }
        }
    }
}

The output window of hte program shows

hats-sold recorded measurement 253
hats-sold recorded measurement 168
hats-sold recorded measurement 473
hats-sold recorded measurement 790

However the ditbet-counters cannot find it as the output shows

C:\Users\me>dotnet-counters monitor -n metric-instr
There is no active process with the given name: metric-instr
1

There are 1 best solutions below

0
junkone On

Credit to @alexanderBurov as above:

dotnet-counters monitor -n ConsoleApp7