System. Diagnostics. Metrics . Net # 6 # explanation of new index API

Time:2022-5-24

preface

Workmates Net 6 preview 7 has been released on August 10. In addition to many function updates and performance improvements, a new index API, system. Net, has also been added in preview 7 Diagnostics. Metrics, in order to make the application more observable, was released before Net 5, activity is also enhanced to activitysource. The main reason is Net runtime team and opentelemetry Net sig conducted in – depth cooperation and jointly developed opentelemetry Net indicator plan.

Metric support plans

Metrics APIs Design

Current system Diagnostics. Metrics API can only be used in Net preview 7. Of course, it will also be like system Text. Like the JSON library, it is released to the nuget platform for other versions Net project access.

Index introduction

Several main classes are introduced below

  • Meter is used to create and track indicators
  • Meterlistener is used to monitor the update of the value of indicator instrument
  • Counter counter is generally used to record the accumulated value, such as the number of errors and requests in the program
  • Histogram histogram, which records the statistical value, such as the response time of each interface, and then summarizes it according to the time
  • Observablecounter can observe the counter and generally record the accumulated value, such as CPU time, etc
  • Observable gauge is an observable dashboard that you can use to record application memory, GC memory, etc

Meter

The meter class is used to create various indicator instruments, including counters, histograms, dashboard indicators, etc. the meter class contains the name and version attributes. You can set the name and version of the meter.


var meter = new Meter("meter","v1.0");

var requestCount = meter.CreateCounter<long>("RequestCount");

var responseTime = meter.CreateHistogram<long>("ResponseTime");

// ...

MeterListener

Meterlistener can be used to monitor the value changes of indicator components. Similarly, there is also an activitylistener.


MeterListener listener = new MeterListener();  

listener.InstrumentPublished = (instrument, meterListener) =>
{
    Console.WriteLine($"EnableMeasurementEvents {instrument.Name} ");
    meterListener.EnableMeasurementEvents(instrument);
};

listener.SetMeasurementEventCallback<long>((instrument, measurement, tags, state) =>
{
    Console.WriteLine($"Instrument: {instrument.Name} has recorded the measurement {measurement}");
});

listener.MeasurementsCompleted = (instrument, state) =>
{
    listener.DisableMeasurementEvents(instrument);
};

listener.Start();

attribute

  • Instrumentpublished when using the meter class to create an indicator instrument, this callback can receive the created indicator information.
  • Measurementscompleted when the collection of indicators is stopped, this callback can receive the corresponding indicator information, usually by executing the dispose () method of meter and meterlistener

method

  • Enablemeasurementevents enables the listening of the corresponding indicator instrument
  • Disablemeasurementevents turn off the listening of the corresponding indicator instrument
  • Setmeasurementeventcallback sets the callback of the measurement value update of the indicator instrument
  • Recordobservable instruments records the current measured values of all observable instruments monitored.
  • Start start the monitoring indicator instrument.

Counter counter

Counter is a counter indicator, which can be used to record the accumulated value. It is very simple to use. In the following example, the number of requests of the program is simulated and recorded. First, call createcounter function to create a counter indicator requestcount, and then call add method to accumulate the counter.


Meter meter = new Meter("meter","v1.0");

var requestCount = meter.CreateCounter<long>("RequestCount");

for (int i = 0; i < 10; i++)
{
    requestCount.Add(1);
}

Then use the meterlistener above to listen for counter indicators. The output of the program is as follows:

In the first line, meterlistener detects the requestcount counter created above and turns on the monitoring of indicators. When we call requestcount After adding (1), the meterlistener captures the update of the measurement value of the indicator, and then outputs the corresponding value on the console. It should be noted that the measurementeventcallback callback method will only capture the measurement value of each update of the indicator, not the total number after summary, so the output here is 1.

Histogram histogram

Histogram is a histogram indicator that records statistical values. For example, it records the response time of each interface and then summarizes it according to the time. It is similar to counter, but the dimension of the indicator is different. Moreover, histogram uses the record () method to record the value of each time instead of the add () method.


Meter meter = new Meter("meter","v1.0");

var responseTime = meter.CreateHistogram<long>("ResponseTime");

for (int i = 0; i < 10; i++)
{
    var cost = new Random().Next(100,1000);

    responseTime.Record(cost);
}

The response time of the interface is represented by a random number, and the output is as follows:

Observablecounter observable counter

Observablecounter is an observable counter. Unlike counter, to create observablecounter, you need to pass in a func delegate to return a measurement value. Of course, you don’t need to call the add() record() method manually. You only need to call the recordobservableinstruments method of meterlistener regularly to obtain the current indicator measurement value.


    class Program
    {
        static async Task Main(string[] args)
        {

            MeterListener listener = new MeterListener();

            Start(listener);

            AutoRecord(listener);
            

            Meter meter = new Meter("meter","v1.0");

            _ = meter.CreateObservableCounter<long>("CPU_Counter",() => new Random().Next(100,1000));

            Console.ReadKey();
        }

        static void Start(MeterListener listener)
        {
            listener.InstrumentPublished = (instrument, meterListener) =>
            {
                Console.WriteLine($"EnableMeasurementEvents {instrument.Name} ");
                meterListener.EnableMeasurementEvents(instrument);
            };

            listener.SetMeasurementEventCallback<long>((instrument, measurement, tags, state) =>
            {
                Console.WriteLine($"Instrument: {instrument.Name} has recorded the measurement {measurement}");
            });

            listener.MeasurementsCompleted = (instrument, state) =>
            {
                listener.DisableMeasurementEvents(instrument);
            };

            listener.Start();

        }

        static void AutoRecord(MeterListener listener)
        {
            var cts = new CancellationTokenSource();

            _ = Task.Run(async () => {

                while (!cts.IsCancellationRequested)
                {
                    await Task.Delay(3000);

                    listener.RecordObservableInstruments();

                }

            });

        }

    }

Observablegauge dashboard indicators

This is easy to understand. You can use it to record the application memory, GC memory, etc. it is also an observable indicator. You also need to pass in a func delegate that returns the measured value.


MeterListener listener = new MeterListener();

Start(listener);

AutoRecord(listener);

Meter meter = new Meter("meter","v1.0");

_ = meter.CreateObservableGauge<long>("GC_Memory_Gauge",() => GC.GetTotalMemory(false));

Console.ReadKey();

The output of the program is as follows:

summary

This paper mainly introduces Net 6 index API system Diagnostics. Metrics, through these APIs, can easily collect application indicator data, but this article does not seem to mention the aggregation and summary of data? Don’t worry, the runtime team has developed a series of high-performance aggregation APIs for the corresponding index APIs, which are expected to be available in Net 6 preview 8 release update!

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support developpaer.