public EventuousMetrics()
    {
        _meter = EventuousDiagnostics.GetMeter(MeterName);

        var eventStoreMetric = _meter.CreateHistogram <double>(
            Constants.Components.EventStore,
            "ms",
            "Event store operation duration, milliseconds"
            );

        var appServiceMetric = _meter.CreateHistogram <double>(
            Constants.Components.AppService,
            "ms",
            "Application service operation duration, milliseconds"
            );

        _listener = new ActivityListener {
            ShouldListenTo  = x => x.Name == EventuousDiagnostics.InstrumentationName,
            Sample          = (ref ActivityCreationOptions <ActivityContext> _) => ActivitySamplingResult.AllData,
            ActivityStopped = Record
        };

        ActivitySource.AddActivityListener(_listener);

        void Record(Activity activity)
        {
            var dot = activity.OperationName.IndexOf('.');

            if (dot == -1)
            {
                return;
            }

            var prefix = activity.OperationName[..dot];
Exemple #2
0
        private void MultithreadedHistogramTest <T>(long[] expected, T[] values)
            where T : struct, IComparable
        {
            var bucketCounts = new long[11];
            var metricReader = new BaseExportingMetricReader(new TestExporter <Metric>(batch =>
            {
                foreach (var metric in batch)
                {
                    foreach (var metricPoint in metric.GetMetricPoints())
                    {
                        bucketCounts = metricPoint.GetHistogramBuckets().RunningBucketCounts;
                    }
                }
            }));

            using var meter         = new Meter($"{Utils.GetCurrentMethodName()}.{typeof(T).Name}");
            using var meterProvider = Sdk.CreateMeterProviderBuilder()
                                      .AddMeter(meter.Name)
                                      .AddReader(metricReader)
                                      .Build();

            var argsToThread = new UpdateThreadArguments <T>
            {
                Instrument                 = meter.CreateHistogram <T>("histogram"),
                MreToBlockUpdateThread     = new ManualResetEvent(false),
                MreToEnsureAllThreadsStart = new ManualResetEvent(false),
                ValuesToRecord             = values,
            };

            Thread[] t = new Thread[numberOfThreads];
            for (int i = 0; i < numberOfThreads; i++)
            {
                t[i] = new Thread(HistogramUpdateThread <T>);
                t[i].Start(argsToThread);
            }

            argsToThread.MreToEnsureAllThreadsStart.WaitOne();
            Stopwatch sw = Stopwatch.StartNew();

            argsToThread.MreToBlockUpdateThread.Set();

            for (int i = 0; i < numberOfThreads; i++)
            {
                t[i].Join();
            }

            this.output.WriteLine($"Took {sw.ElapsedMilliseconds} msecs. Total threads: {numberOfThreads}, each thread doing {numberOfMetricUpdateByEachThread * values.Length} recordings.");

            metricReader.Collect();

            Assert.Equal(expected, bucketCounts);
        }
Exemple #3
0
        public void ApplicationInsights_Metrics_Collection_Raises_Histogram_Metrics()
        {
            // arrange
            const string gateway = "foogateway";

            using var meter = new Meter("LoRaWan", "1.0");
            const int value     = 1;
            var       histogram = meter.CreateHistogram <int>(HistogramMetric.Name);

            // act
            this.applicationInsightsMetricExporter.Start();
            histogram.Record(value, KeyValuePair.Create(MetricRegistry.ConcentratorIdTagName, (object)gateway));

            // assert
            this.trackValueMock.Verify(me => me.Invoke(It.Is <Metric>(m => m.Identifier.MetricNamespace == MetricRegistry.Namespace &&
                                                                      m.Identifier.MetricId == HistogramMetric.Name),
                                                       value,
                                                       new[] { gateway }),
                                       Times.Once);
        }
Exemple #4
0
        private static string WriteHistogram(Meter meter, KeyValuePair <string, object>[] tags, string tagsExpected)
        {
            var histogram = meter.CreateHistogram <long>("histogram_name");

            histogram.Record(100, tags);
            histogram.Record(18, tags);

            return("# TYPE histogram_name histogram\nhistogram_name_sum{key1=\"value1\",key2=\"value2\"} 118 1633041000000\n"
                   + "histogram_name_count{key1=\"value1\",key2=\"value2\"} 2 1633041000000\n"
                   + "histogram_name_bucket{key1=\"value1\",key2=\"value2\",le=\"0\"} 0 1633041000000\n"
                   + "histogram_name_bucket{key1=\"value1\",key2=\"value2\",le=\"5\"} 0 1633041000000\n"
                   + "histogram_name_bucket{key1=\"value1\",key2=\"value2\",le=\"10\"} 0 1633041000000\n"
                   + "histogram_name_bucket{key1=\"value1\",key2=\"value2\",le=\"25\"} 1 1633041000000\n"
                   + "histogram_name_bucket{key1=\"value1\",key2=\"value2\",le=\"50\"} 1 1633041000000\n"
                   + "histogram_name_bucket{key1=\"value1\",key2=\"value2\",le=\"75\"} 1 1633041000000\n"
                   + "histogram_name_bucket{key1=\"value1\",key2=\"value2\",le=\"100\"} 2 1633041000000\n"
                   + "histogram_name_bucket{key1=\"value1\",key2=\"value2\",le=\"250\"} 2 1633041000000\n"
                   + "histogram_name_bucket{key1=\"value1\",key2=\"value2\",le=\"500\"} 2 1633041000000\n"
                   + "histogram_name_bucket{key1=\"value1\",key2=\"value2\",le=\"1000\"} 2 1633041000000\n"
                   + "histogram_name_bucket{key1=\"value1\",key2=\"value2\",le=\"+Inf\"} 2 1633041000000\n");
        }
Exemple #5
0
        public MessageDispatcher(
            NetworkServerConfiguration configuration,
            ILoRaDeviceRegistry deviceRegistry,
            ILoRaDeviceFrameCounterUpdateStrategyProvider frameCounterUpdateStrategyProvider,
            IJoinRequestMessageHandler joinRequestHandler,
            ILoggerFactory loggerFactory,
            ILogger <MessageDispatcher> logger,
            Meter meter)
        {
            this.configuration  = configuration ?? throw new ArgumentNullException(nameof(configuration));
            this.deviceRegistry = deviceRegistry;
            this.frameCounterUpdateStrategyProvider = frameCounterUpdateStrategyProvider;

            // Register frame counter initializer
            // It will take care of seeding ABP devices created here for single gateway scenarios
            this.deviceRegistry.RegisterDeviceInitializer(new FrameCounterLoRaDeviceInitializer(configuration.GatewayID, frameCounterUpdateStrategyProvider));

            this.joinRequestHandler = joinRequestHandler;
            this.loggerFactory      = loggerFactory;
            this.logger             = logger;
            this.d2cMessageDeliveryLatencyHistogram = meter?.CreateHistogram <double>(MetricRegistry.D2CMessageDeliveryLatency);
        }
        public void When_Histogram_Series_Is_Recorded_Should_Export_To_Prometheus()
        {
            // arrange
            const string gatewayId = "fooGateway";
            var          values    = new[] { 1, 3, 10, -2 };

            this.prometheusMetricExporter.Start();

            // act
            using var meter = new Meter("LoRaWan", "1.0");
            var histogram = meter.CreateHistogram <int>(Histogram.Name);

            foreach (var value in values)
            {
                histogram.Record(value, KeyValuePair.Create(MetricRegistry.ConcentratorIdTagName, (object?)gatewayId));
            }

            // assert
            foreach (var value in values)
            {
                this.recordHistogramMock.Verify(c => c.Invoke(Histogram.Name, new[] { gatewayId }, value), Times.Once);
            }
        }
Exemple #7
0
        internal static object Run(MetricsOptions options)
        {
            using var meter = new Meter("TestMeter");

            var providerBuilder = Sdk.CreateMeterProviderBuilder()
                                  .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("myservice"))
                                  .AddMeter(meter.Name); // All instruments from this meter are enabled.

            if (options.UseExporter.ToLower() == "otlp")
            {
                /*
                 * Prerequisite to run this example:
                 * Set up an OpenTelemetry Collector to run on local docker.
                 *
                 * Open a terminal window at the examples/Console/ directory and
                 * launch the OpenTelemetry Collector with an OTLP receiver, by running:
                 *
                 *  - On Unix based systems use:
                 *     docker run --rm -it -p 4317:4317 -v $(pwd):/cfg otel/opentelemetry-collector:0.33.0 --config=/cfg/otlp-collector-example/config.yaml
                 *
                 *  - On Windows use:
                 *     docker run --rm -it -p 4317:4317 -v "%cd%":/cfg otel/opentelemetry-collector:0.33.0 --config=/cfg/otlp-collector-example/config.yaml
                 *
                 * Open another terminal window at the examples/Console/ directory and
                 * launch the OTLP example by running:
                 *
                 *     dotnet run metrics --useExporter otlp
                 *
                 * The OpenTelemetry Collector will output all received metrics to the stdout of its terminal.
                 *
                 */

                // Adding the OtlpExporter creates a GrpcChannel.
                // This switch must be set before creating a GrpcChannel/HttpClient when calling an insecure gRPC service.
                // See: https://docs.microsoft.com/aspnet/core/grpc/troubleshoot#call-insecure-grpc-services-with-net-core-client
                AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

                providerBuilder
                .AddOtlpExporter(o =>
                {
                    o.MetricExportIntervalMilliseconds = options.DefaultCollectionPeriodMilliseconds;
                    o.AggregationTemporality           = options.IsDelta ? AggregationTemporality.Delta : AggregationTemporality.Cumulative;
                });
            }
            else
            {
                providerBuilder
                .AddConsoleExporter(o =>
                {
                    o.MetricExportIntervalMilliseconds = options.DefaultCollectionPeriodMilliseconds;
                    o.AggregationTemporality           = options.IsDelta ? AggregationTemporality.Delta : AggregationTemporality.Cumulative;
                });
            }

            using var provider = providerBuilder.Build();

            Counter <int> counter = null;

            if (options.FlagCounter ?? true)
            {
                counter = meter.CreateCounter <int>("counter", "things", "A count of things");
            }

            Histogram <int> histogram = null;

            if (options.FlagHistogram ?? false)
            {
                histogram = meter.CreateHistogram <int>("histogram");
            }

            if (options.FlagGauge ?? false)
            {
                var observableCounter = meter.CreateObservableGauge("gauge", () =>
                {
                    return(new List <Measurement <int> >()
                    {
                        new Measurement <int>(
                            (int)Process.GetCurrentProcess().PrivateMemorySize64,
                            new KeyValuePair <string, object>("tag1", "value1")),
                    });
                });
            }

            var cts = new CancellationTokenSource();

            var tasks = new List <Task>();

            for (int i = 0; i < options.NumTasks; i++)
            {
                var taskno = i;

                tasks.Add(Task.Run(() =>
                {
                    System.Console.WriteLine($"Task started {taskno + 1}/{options.NumTasks}.");

                    var loops = 0;

                    while (!cts.IsCancellationRequested)
                    {
                        if (options.MaxLoops > 0 && loops >= options.MaxLoops)
                        {
                            break;
                        }

                        histogram?.Record(10);

                        histogram?.Record(
                            100,
                            new KeyValuePair <string, object>("tag1", "value1"));

                        histogram?.Record(
                            200,
                            new KeyValuePair <string, object>("tag1", "value2"),
                            new KeyValuePair <string, object>("tag2", "value2"));

                        histogram?.Record(
                            100,
                            new KeyValuePair <string, object>("tag1", "value1"));

                        histogram?.Record(
                            200,
                            new KeyValuePair <string, object>("tag2", "value2"),
                            new KeyValuePair <string, object>("tag1", "value2"));

                        counter?.Add(10);

                        counter?.Add(
                            100,
                            new KeyValuePair <string, object>("tag1", "value1"));

                        counter?.Add(
                            200,
                            new KeyValuePair <string, object>("tag1", "value2"),
                            new KeyValuePair <string, object>("tag2", "value2"));

                        counter?.Add(
                            100,
                            new KeyValuePair <string, object>("tag1", "value1"));

                        counter?.Add(
                            200,
                            new KeyValuePair <string, object>("tag2", "value2"),
                            new KeyValuePair <string, object>("tag1", "value2"));

                        loops++;
                    }
                }));
            }

            cts.CancelAfter(options.RunTime);
            System.Console.WriteLine($"Wait for {options.RunTime} milliseconds.");
            while (!cts.IsCancellationRequested)
            {
                Task.Delay(1000).Wait();
            }

            Task.WaitAll(tasks.ToArray());

            return(null);
        }
Exemple #8
0
        public void ViewToProduceCustomHistogramBound()
        {
            using var meter = new Meter(Utils.GetCurrentMethodName());
            var exportedItems = new List <Metric>();
            var boundaries    = new double[] { 10, 20 };

            using var meterProvider = Sdk.CreateMeterProviderBuilder()
                                      .AddMeter(meter.Name)
                                      .AddView("MyHistogram", new ExplicitBucketHistogramConfiguration()
            {
                Name = "MyHistogramDefaultBound"
            })
                                      .AddView("MyHistogram", new ExplicitBucketHistogramConfiguration()
            {
                Boundaries = boundaries
            })
                                      .AddInMemoryExporter(exportedItems)
                                      .Build();

            var histogram = meter.CreateHistogram <long>("MyHistogram");

            histogram.Record(-10);
            histogram.Record(0);
            histogram.Record(1);
            histogram.Record(9);
            histogram.Record(10);
            histogram.Record(11);
            histogram.Record(19);
            meterProvider.ForceFlush(MaxTimeToAllowForFlush);
            Assert.Equal(2, exportedItems.Count);
            var metricDefault = exportedItems[0];
            var metricCustom  = exportedItems[1];

            Assert.Equal("MyHistogramDefaultBound", metricDefault.Name);
            Assert.Equal("MyHistogram", metricCustom.Name);

            List <MetricPoint> metricPointsDefault = new List <MetricPoint>();

            foreach (ref readonly var mp in metricDefault.GetMetricPoints())
            {
                metricPointsDefault.Add(mp);
            }

            Assert.Single(metricPointsDefault);
            var histogramPoint = metricPointsDefault[0];

            var count = histogramPoint.GetHistogramCount();
            var sum   = histogramPoint.GetHistogramSum();

            Assert.Equal(40, sum);
            Assert.Equal(7, count);

            int index                = 0;
            int actualCount          = 0;
            var expectedBucketCounts = new long[] { 2, 1, 2, 2, 0, 0, 0, 0, 0, 0, 0 };

            foreach (var histogramMeasurement in histogramPoint.GetHistogramBuckets())
            {
                Assert.Equal(expectedBucketCounts[index], histogramMeasurement.BucketCount);
                index++;
                actualCount++;
            }

            Assert.Equal(Metric.DefaultHistogramBounds.Length + 1, actualCount);

            List <MetricPoint> metricPointsCustom = new List <MetricPoint>();

            foreach (ref readonly var mp in metricCustom.GetMetricPoints())
            {
                metricPointsCustom.Add(mp);
            }

            Assert.Single(metricPointsCustom);
            histogramPoint = metricPointsCustom[0];

            count = histogramPoint.GetHistogramCount();
            sum   = histogramPoint.GetHistogramSum();

            Assert.Equal(40, sum);
            Assert.Equal(7, count);

            index                = 0;
            actualCount          = 0;
            expectedBucketCounts = new long[] { 5, 2, 0 };
            foreach (var histogramMeasurement in histogramPoint.GetHistogramBuckets())
            {
                Assert.Equal(expectedBucketCounts[index], histogramMeasurement.BucketCount);
                index++;
                actualCount++;
            }

            Assert.Equal(boundaries.Length + 1, actualCount);
        }
Exemple #9
0
        public void ViewConflict_TwoIdenticalInstruments_TwoViews_DifferentHistogramBounds()
        {
            var exportedItems = new List <Metric>();

            using var meter = new Meter($"{Utils.GetCurrentMethodName()}");
            var meterProviderBuilder = Sdk.CreateMeterProviderBuilder()
                                       .AddMeter(meter.Name)
                                       .AddView((instrument) =>
            {
                return(new ExplicitBucketHistogramConfiguration {
                    Boundaries = new[] { 5.0, 10.0 }
                });
            })
                                       .AddView((instrument) =>
            {
                return(new ExplicitBucketHistogramConfiguration {
                    Boundaries = new[] { 10.0, 20.0 }
                });
            })
                                       .AddInMemoryExporter(exportedItems);

            using var meterProvider = meterProviderBuilder.Build();

            var instrument1 = meter.CreateHistogram <long>("name");
            var instrument2 = meter.CreateHistogram <long>("name");

            instrument1.Record(15);
            instrument2.Record(15);

            meterProvider.ForceFlush(MaxTimeToAllowForFlush);

            Assert.Equal(2, exportedItems.Count);
            var metric1 = exportedItems[0];
            var metric2 = exportedItems[1];

            Assert.Equal("name", exportedItems[0].Name);
            Assert.Equal("name", exportedItems[1].Name);

            var metricPoints = new List <MetricPoint>();

            foreach (ref readonly var mp in metric1.GetMetricPoints())
            {
                metricPoints.Add(mp);
            }

            Assert.Single(metricPoints);
            var metricPoint = metricPoints[0];

            Assert.Equal(2, metricPoint.GetHistogramCount());
            Assert.Equal(30, metricPoint.GetHistogramSum());

            var index                = 0;
            var actualCount          = 0;
            var expectedBucketCounts = new long[] { 0, 0, 2 };

            foreach (var histogramMeasurement in metricPoint.GetHistogramBuckets())
            {
                Assert.Equal(expectedBucketCounts[index], histogramMeasurement.BucketCount);
                index++;
                actualCount++;
            }

            metricPoints = new List <MetricPoint>();
            foreach (ref readonly var mp in metric2.GetMetricPoints())
            {
                metricPoints.Add(mp);
            }

            Assert.Single(metricPoints);
            metricPoint = metricPoints[0];
            Assert.Equal(2, metricPoint.GetHistogramCount());
            Assert.Equal(30, metricPoint.GetHistogramSum());

            index                = 0;
            actualCount          = 0;
            expectedBucketCounts = new long[] { 0, 2, 0 };
            foreach (var histogramMeasurement in metricPoint.GetHistogramBuckets())
            {
                Assert.Equal(expectedBucketCounts[index], histogramMeasurement.BucketCount);
                index++;
                actualCount++;
            }
        }
 public HttpInMetricsListener(string name, Meter meter)
     : base(name)
 {
     this.meter = meter;
     this.httpServerDuration = meter.CreateHistogram <double>("http.server.duration", "ms", "measures the duration of the inbound HTTP request");
 }
Exemple #11
0
        public void TestHistogramToOltpMetric(string name, string description, string unit, long?longValue, double?doubleValue, AggregationTemporality aggregationTemporality, params object[] keysValues)
        {
            var metrics = new List <Metric>();

            var metricReader = new BaseExportingMetricReader(new InMemoryExporter <Metric>(metrics));

            metricReader.Temporality = aggregationTemporality;

            using var meter    = new Meter(Utils.GetCurrentMethodName());
            using var provider = Sdk.CreateMeterProviderBuilder()
                                 .AddMeter(meter.Name)
                                 .AddReader(metricReader)
                                 .Build();

            var attributes = ToAttributes(keysValues).ToArray();

            if (longValue.HasValue)
            {
                var histogram = meter.CreateHistogram <long>(name, unit, description);
                histogram.Record(longValue.Value, attributes);
            }
            else
            {
                var histogram = meter.CreateHistogram <double>(name, unit, description);
                histogram.Record(doubleValue.Value, attributes);
            }

            provider.ForceFlush();

            var batch = new Batch <Metric>(metrics.ToArray(), metrics.Count);

            var request = new OtlpCollector.ExportMetricsServiceRequest();

            request.AddMetrics(ResourceBuilder.CreateEmpty().Build().ToOtlpResource(), batch);

            var resourceMetric = request.ResourceMetrics.Single();
            var instrumentationLibraryMetrics = resourceMetric.InstrumentationLibraryMetrics.Single();
            var actual = instrumentationLibraryMetrics.Metrics.Single();

            Assert.Equal(name, actual.Name);
            Assert.Equal(description ?? string.Empty, actual.Description);
            Assert.Equal(unit ?? string.Empty, actual.Unit);

            Assert.Equal(OtlpMetrics.Metric.DataOneofCase.Histogram, actual.DataCase);

            Assert.Null(actual.Gauge);
            Assert.Null(actual.Sum);
            Assert.NotNull(actual.Histogram);
            Assert.Null(actual.ExponentialHistogram);
            Assert.Null(actual.Summary);

            var otlpAggregationTemporality = aggregationTemporality == AggregationTemporality.Cumulative
                ? OtlpMetrics.AggregationTemporality.Cumulative
                : OtlpMetrics.AggregationTemporality.Delta;

            Assert.Equal(otlpAggregationTemporality, actual.Histogram.AggregationTemporality);

            Assert.Single(actual.Histogram.DataPoints);
            var dataPoint = actual.Histogram.DataPoints.First();

            Assert.True(dataPoint.StartTimeUnixNano > 0);
            Assert.True(dataPoint.TimeUnixNano > 0);

            Assert.Equal(1UL, dataPoint.Count);

            if (longValue.HasValue)
            {
                Assert.Equal((double)longValue, dataPoint.Sum);
            }
            else
            {
                Assert.Equal(doubleValue, dataPoint.Sum);
            }

            int bucketIndex;

            for (bucketIndex = 0; bucketIndex < dataPoint.ExplicitBounds.Count; ++bucketIndex)
            {
                if (dataPoint.Sum <= dataPoint.ExplicitBounds[bucketIndex])
                {
                    break;
                }

                Assert.Equal(0UL, dataPoint.BucketCounts[bucketIndex]);
            }

            Assert.Equal(1UL, dataPoint.BucketCounts[bucketIndex]);

            if (attributes.Length > 0)
            {
                OtlpTestHelpers.AssertOtlpAttributes(attributes, dataPoint.Attributes);
            }
            else
            {
                Assert.Empty(dataPoint.Attributes);
            }

            Assert.Empty(dataPoint.Exemplars);

#pragma warning disable CS0612 // Type or member is obsolete
            Assert.Null(actual.IntGauge);
            Assert.Null(actual.IntSum);
            Assert.Null(actual.IntHistogram);
            Assert.Empty(dataPoint.Labels);
#pragma warning restore CS0612 // Type or member is obsolete
        }
Exemple #12
0
        internal static object Run(MetricsOptions options)
        {
            using var meter = new Meter("TestMeter");

            var providerBuilder = Sdk.CreateMeterProviderBuilder()
                                  .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("myservice"))
                                  .AddMeter(meter.Name); // All instruments from this meter are enabled.

            if (options.UseExporter.Equals("otlp", StringComparison.OrdinalIgnoreCase))
            {
                /*
                 * Prerequisite to run this example:
                 * Set up an OpenTelemetry Collector to run on local docker.
                 *
                 * Open a terminal window at the examples/Console/ directory and
                 * launch the OpenTelemetry Collector with an OTLP receiver, by running:
                 *
                 *  - On Unix based systems use:
                 *     docker run --rm -it -p 4317:4317 -v $(pwd):/cfg otel/opentelemetry-collector:0.33.0 --config=/cfg/otlp-collector-example/config.yaml
                 *
                 *  - On Windows use:
                 *     docker run --rm -it -p 4317:4317 -v "%cd%":/cfg otel/opentelemetry-collector:0.33.0 --config=/cfg/otlp-collector-example/config.yaml
                 *
                 * Open another terminal window at the examples/Console/ directory and
                 * launch the OTLP example by running:
                 *
                 *     dotnet run metrics --useExporter otlp
                 *
                 * The OpenTelemetry Collector will output all received metrics to the stdout of its terminal.
                 *
                 */

                // Adding the OtlpExporter creates a GrpcChannel.
                // This switch must be set before creating a GrpcChannel when calling an insecure gRPC service.
                // See: https://docs.microsoft.com/aspnet/core/grpc/troubleshoot#call-insecure-grpc-services-with-net-core-client
                AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

                providerBuilder
                .AddOtlpExporter((exporterOptions, metricReaderOptions) =>
                {
                    exporterOptions.Protocol = options.UseGrpc ? OtlpExportProtocol.Grpc : OtlpExportProtocol.HttpProtobuf;

                    metricReaderOptions.PeriodicExportingMetricReaderOptions.ExportIntervalMilliseconds = options.DefaultCollectionPeriodMilliseconds;
                    metricReaderOptions.TemporalityPreference = options.IsDelta ? MetricReaderTemporalityPreference.Delta : MetricReaderTemporalityPreference.Cumulative;
                });
            }
            else
            {
                providerBuilder
                .AddConsoleExporter((exporterOptions, metricReaderOptions) =>
                {
                    exporterOptions.Targets = ConsoleExporterOutputTargets.Console;

                    metricReaderOptions.PeriodicExportingMetricReaderOptions.ExportIntervalMilliseconds = options.DefaultCollectionPeriodMilliseconds;
                    metricReaderOptions.TemporalityPreference = options.IsDelta ? MetricReaderTemporalityPreference.Delta : MetricReaderTemporalityPreference.Cumulative;
                });
            }

            using var provider = providerBuilder.Build();

            Counter <int> counter = null;

            if (options.FlagCounter ?? true)
            {
                counter = meter.CreateCounter <int>("counter", "things", "A count of things");
            }

            Histogram <int> histogram = null;

            if (options.FlagHistogram ?? false)
            {
                histogram = meter.CreateHistogram <int>("histogram");
            }

            if (options.FlagGauge ?? false)
            {
                var observableCounter = meter.CreateObservableGauge("gauge", () =>
                {
                    return(new List <Measurement <int> >()
                    {
                        new Measurement <int>(
                            (int)Process.GetCurrentProcess().PrivateMemorySize64,
                            new KeyValuePair <string, object>("tag1", "value1")),
                    });
                });
            }

            System.Console.WriteLine("Press any key to exit.");
            while (!System.Console.KeyAvailable)
            {
                histogram?.Record(10);

                histogram?.Record(
                    100,
                    new KeyValuePair <string, object>("tag1", "value1"));

                histogram?.Record(
                    200,
                    new KeyValuePair <string, object>("tag1", "value2"),
                    new KeyValuePair <string, object>("tag2", "value2"));

                histogram?.Record(
                    100,
                    new KeyValuePair <string, object>("tag1", "value1"));

                histogram?.Record(
                    200,
                    new KeyValuePair <string, object>("tag2", "value2"),
                    new KeyValuePair <string, object>("tag1", "value2"));

                counter?.Add(10);

                counter?.Add(
                    100,
                    new KeyValuePair <string, object>("tag1", "value1"));

                counter?.Add(
                    200,
                    new KeyValuePair <string, object>("tag1", "value2"),
                    new KeyValuePair <string, object>("tag2", "value2"));

                counter?.Add(
                    100,
                    new KeyValuePair <string, object>("tag1", "value1"));

                counter?.Add(
                    200,
                    new KeyValuePair <string, object>("tag2", "value2"),
                    new KeyValuePair <string, object>("tag1", "value2"));

                Task.Delay(500).Wait();
            }

            return(null);
        }
Exemple #13
0
    public static void Main(string[] args)
    {
        using var meterProvider = Sdk.CreateMeterProviderBuilder()
                                  .AddMeter(Meter1.Name)
                                  .AddMeter(Meter2.Name)

                                  // Rename an instrument to new name.
                                  .AddView(instrumentName: "MyCounter", name: "MyCounterRenamed")

                                  // Change Histogram bounds
                                  .AddView(instrumentName: "MyHistogram", new HistogramConfiguration()
        {
            BucketBounds = new double[] { 10, 20 }
        })

                                  // For the instrument "MyCounterCustomTags", aggregate with only the keys "tag1", "tag2".
                                  .AddView(instrumentName: "MyCounterCustomTags", new MetricStreamConfiguration()
        {
            TagKeys = new string[] { "tag1", "tag2" }
        })

                                  // Drop the instrument "MyCounterDrop".
                                  .AddView(instrumentName: "MyCounterDrop", MetricStreamConfiguration.Drop)

                                  // Advanced selection criteria and config via Func<Instrument, MetricStreamConfiguration>
                                  .AddView((instrument) =>
        {
            if (instrument.Meter.Name.Equals("CompanyA.ProductB.Library2") &&
                instrument.GetType().Name.Contains("Histogram"))
            {
                return(new HistogramConfiguration()
                {
                    BucketBounds = new double[] { 10, 20 }
                });
            }

            return(null);
        })

                                  // An instrument which does not match any views
                                  // gets processed with default behavior. (SDK default)
                                  // Uncommenting the following line will
                                  // turn off the above default. i.e any
                                  // instrument which does not match any views
                                  // gets dropped.
                                  // .AddView(instrumentName: "*", new MetricStreamConfiguration() { Aggregation = Aggregation.Drop })
                                  .AddConsoleExporter()
                                  .Build();

        var random = new Random();

        var counter = Meter1.CreateCounter <long>("MyCounter");

        for (int i = 0; i < 20000; i++)
        {
            counter.Add(1, new("tag1", "value1"), new("tag2", "value2"));
        }

        var histogram = Meter1.CreateHistogram <long>("MyHistogram");

        for (int i = 0; i < 20000; i++)
        {
            histogram.Record(random.Next(1, 1000), new("tag1", "value1"), new("tag2", "value2"));
        }

        var counterCustomTags = Meter1.CreateCounter <long>("MyCounterCustomTags");

        for (int i = 0; i < 20000; i++)
        {
            counterCustomTags.Add(1, new("tag1", "value1"), new("tag2", "value2"), new("tag3", "value4"));
        }

        var counterDrop = Meter1.CreateCounter <long>("MyCounterDrop");

        for (int i = 0; i < 20000; i++)
        {
            counterDrop.Add(1, new("tag1", "value1"), new("tag2", "value2"));
        }

        var histogram2 = Meter2.CreateHistogram <long>("MyHistogram2");

        for (int i = 0; i < 20000; i++)
        {
            histogram2.Record(random.Next(1, 1000), new("tag1", "value1"), new("tag2", "value2"));
        }
    }
Exemple #14
0
        public void ViewToProduceCustomHistogramBound()
        {
            using var meter1 = new Meter("ViewToProduceCustomHistogramBoundTest");
            var exportedItems = new List <Metric>();
            var bounds        = new double[] { 10, 20 };

            using var meterProvider = Sdk.CreateMeterProviderBuilder()
                                      .AddMeter(meter1.Name)
                                      .AddView("MyHistogram", new HistogramConfiguration()
            {
                Name = "MyHistogramDefaultBound"
            })
                                      .AddView("MyHistogram", new HistogramConfiguration()
            {
                BucketBounds = bounds
            })
                                      .AddInMemoryExporter(exportedItems)
                                      .Build();

            var histogram = meter1.CreateHistogram <long>("MyHistogram");

            histogram.Record(-10);
            histogram.Record(0);
            histogram.Record(1);
            histogram.Record(9);
            histogram.Record(10);
            histogram.Record(11);
            histogram.Record(19);
            meterProvider.ForceFlush(MaxTimeToAllowForFlush);
            Assert.Equal(2, exportedItems.Count);
            var metricDefault = exportedItems[0];
            var metricCustom  = exportedItems[1];

            Assert.Equal("MyHistogramDefaultBound", metricDefault.Name);
            Assert.Equal("MyHistogram", metricCustom.Name);

            List <MetricPoint> metricPointsDefault = new List <MetricPoint>();

            foreach (ref var mp in metricDefault.GetMetricPoints())
            {
                metricPointsDefault.Add(mp);
            }

            Assert.Single(metricPointsDefault);
            var histogramPoint = metricPointsDefault[0];

            Assert.Equal(40, histogramPoint.DoubleValue);
            Assert.Equal(7, histogramPoint.LongValue);
            Assert.Equal(Metric.DefaultHistogramBounds.Length + 1, histogramPoint.BucketCounts.Length);
            Assert.Equal(2, histogramPoint.BucketCounts[0]);
            Assert.Equal(1, histogramPoint.BucketCounts[1]);
            Assert.Equal(2, histogramPoint.BucketCounts[2]);
            Assert.Equal(2, histogramPoint.BucketCounts[3]);
            Assert.Equal(0, histogramPoint.BucketCounts[4]);
            Assert.Equal(0, histogramPoint.BucketCounts[5]);

            List <MetricPoint> metricPointsCustom = new List <MetricPoint>();

            foreach (ref var mp in metricCustom.GetMetricPoints())
            {
                metricPointsCustom.Add(mp);
            }

            Assert.Single(metricPointsCustom);
            histogramPoint = metricPointsCustom[0];

            Assert.Equal(40, histogramPoint.DoubleValue);
            Assert.Equal(7, histogramPoint.LongValue);
            Assert.Equal(bounds.Length + 1, histogramPoint.BucketCounts.Length);
            Assert.Equal(5, histogramPoint.BucketCounts[0]);
            Assert.Equal(2, histogramPoint.BucketCounts[1]);
            Assert.Equal(0, histogramPoint.BucketCounts[2]);
        }
 public HttpInMetricsListener(Meter meter)
 {
     this.httpServerDuration = meter.CreateHistogram <double>("http.server.duration", "ms", "measures the duration of the inbound HTTP request");
     TelemetryHttpModule.Options.OnRequestStoppedCallback += this.OnStopActivity;
 }
 public HttpHandlerMetricsDiagnosticListener(string name, Meter meter)
     : base(name)
 {
     this.httpClientDuration = meter.CreateHistogram <double>("http.client.duration", "milliseconds", "measure the duration of the outbound HTTP request");
 }