Repository navigation
Description
This is edited by @tarekgh
Runtime Metrics APIs Proposal
At present, the metrics APIs that are exposed do not integrate smoothly with DI. This is because the current support relies on creating Meter objects as static, which cannot be utilized within DI containers. As a solution, this proposal recommends developing new APIs that will enable metrics to work seamlessly with DI.
Meter Factory
The IMeterFactory interface is being introduced, which can be registered with the DI container and utilized to create or obtain Meter objects.
IMeterFactory
namespace System.Diagnostics.Metrics
{
public interface IMeterFactory : IDisposable
{
Meter Create(
string name,
string? version = null,
IEnumerable<KeyValuePair<string, object?>>? tags = null);
}
}A default implementation will be offered, which should be adequate for most use cases. Nonetheless, users may choose to provide their own implementation for alternative purposes, such as testing.
Meter factories will be accountable for the following responsibilities:
- Creating a new meter.
- Attaching the factory instance to the Meter constructor for all created Meter objects. Additional details regarding this will be addressed later in the metrics APIs' additions.
- Storing created meters in a cache and returning a cached instance if a meter with the same parameters (name, version, and tags) is requested.
- Disposing of all cached Meter objects upon factory disposal.
DI IMeterFactory Registration
The default IMeterFactory registration can be done by the API:
namespace Microsoft.Extensions.Metrics
{
public static class MetricsServiceExtensions
{
public static IServiceCollection AddMetrics(this IServiceCollection services);
}
}Core Metrics APIs Addition
The proposed modifications aim to facilitate the following:
- Inclusion of default tags to the Meter
- Addition of default tags to the instruments
- Incorporation of scope into the Meter involves assigning an IMeterFactory object to the Meter, which serves as a marker for all Meters associated with a particular factory.
- The Meter will now cache non-Observable instruments internally to prevent re-creation when attempting to recreate the same instrument with identical parameters such as name, unit, tags, and generic type.
namespace System.Diagnostics.Metrics
{
public abstract class Instrument
{
protected Instrument(
Meter meter,
string name,
string? unit,
string? description,
IEnumerable<KeyValuePair<string, object?>>? tags);
public IEnumerable<KeyValuePair<string, object?>>? Tags { get; }
}
public abstract class Instrument<T> : Instrument where T : struct
{
protected Instrument(
Meter meter,
string name,
string? unit,
string? description, IEnumerable<KeyValuePair<string, object?>>? tags);
}
public abstract class ObservableInstrument<T> : Instrument where T : struct
{
protected ObservableInstrument(
Meter meter,
string name,
string? unit,
string? description,
IEnumerable<KeyValuePair<string, object?>> tags);
}
public class Meter : IDisposable
{
public Meter(
string name,
string? version,
IEnumerable<KeyValuePair<string, object?>>? tags,
IMeterFactory? factory = null);
public IEnumerable<KeyValuePair<string, object?>>? Tags { get ; }}
public IMeterFactory? Factory { get; }
public Counter<T> CreateCounter<T>(
string name,
string? unit,
string? description,
IEnumerable<KeyValuePair<string, object?>> tags) where T : struct;
public UpDownCounter<T> CreateUpDownCounter<T>(
string name,
string? unit,
string? description,
IEnumerable<KeyValuePair<string, object?>> tags) where T : struct;
public Histogram<T> CreateHistogram<T>(
string name,
string? unit,
string? description,
IEnumerable<KeyValuePair<string, object?>> tags) where T : struct;
public ObservableCounter<T> CreateObservableCounter<T>(
string name,
Func<T> observeValue,
string? unit,
string? description,
IEnumerable<KeyValuePair<string, object?>> tags) where T : struct;
public ObservableCounter<T> CreateObservableCounter<T>(
string name,
Func<Measurement<T>> observeValue,
string? unit,
string? description,
IEnumerable<KeyValuePair<string, object?>> tags) where T : struct;
public ObservableCounter<T> CreateObservableCounter<T>(
string name,
Func<IEnumerable<Measurement<T>>> observeValues,
string? unit,
string? description,
IEnumerable<KeyValuePair<string, object?>> tags) where T : struct;
public ObservableUpDownCounter<T> CreateObservableUpDownCounter<T>(
string name,
Func<T> observeValue,
string? unit,
string? description,
IEnumerable<KeyValuePair<string, object?>> tags) where T : struct;
public ObservableUpDownCounter<T> CreateObservableUpDownCounter<T>(
string name,
Func<Measurement<T>> observeValue,
string? unit,
string? description,
IEnumerable<KeyValuePair<string, object?>> tags) where T : struct;
public ObservableUpDownCounter<T> CreateObservableUpDownCounter<T>(
string name,
Func<IEnumerable<Measurement<T>>> observeValues,
string? unit,
string? description,
IEnumerable<KeyValuePair<string, object?>> tags) where T : struct;
public ObservableGauge<T> CreateObservableGauge<T>(
string name,
Func<T> observeValue,
string? unit,
string? description,
IEnumerable<KeyValuePair<string, object?>> tags) where T : struct;
public ObservableGauge<T> CreateObservableGauge<T>(
string name,
Func<Measurement<T>> observeValue,
string? unit,
string? description,
IEnumerable<KeyValuePair<string, object?>> tags) where T : struct;
public ObservableGauge<T> CreateObservableGauge<T>(
string name,
Func<IEnumerable<Measurement<T>>> observeValues,
string? unit,
string? description,
IEnumerable<KeyValuePair<string, object?>> tags) where T : struct;
}Testing Helper
The InstrumentRecorder class has been introduced to facilitate metric testing with DI. With this class, it is straightforward to monitor a particular instrument and its meter readings, and then generate reports on the values published by the instrument.
namespace Microsoft.Extensions.Metrics
{
public sealed class InstrumentRecorder<T> : IDisposable where T : struct
{
public InstrumentRecorder(Instrument instrument);
public InstrumentRecorder(
IMeterFactory? meterFactory,
string meterName,
string instrumentName);
public InstrumentRecorder(
Meter meter,
string instrumentName);
public Instrument Instrument { get; }
public IEnumerable<Measurement<T>> GetMeasurements();
public void Dispose();
}
}Code Example
//
// Register Metrics
//
services.AddMetrics();
//
// Access the MeterFactory
//
IMeterFactory meterFactory = serviceProvider.GetRequiredService<IMeterFactory>();
//
// Create Meter
//
Meter meter = meterFactory.Create(
"MeterName",
"version",
new TagList()
{
{ "Key1", "Value1" },
{ "Key2", "Value2" }
});
//
// Create Instrument
//
Counter<int> counter = meter.CreateCounter<int>(
"CounterName",
"cm",
"Test counter 1",
new TagList() { { "K1", "V1" } });
//
// Test instrument published values
//
var recorder = new InstrumentRecorder<int>(meterFactory, "MeterName", "CounterName");
// can do the following too:
// var recorder = new InstrumentRecorder<int>(counter);
counter. Add(1);
Assert.Equal(1, recorder.GetMeasurements().ElementAt(0));end of @tarekgh edit and start of old description
Background and motivation
.NET exposes Meter API to instrument code for collecting metrics. Currently the Meter is a class which doesn't work well with DI (Dependency Injection) based model. In order to create a meter object a developer currently need to create an object of the Meter class and pass the meter name, something like this
var meter = new Meter("myMeter");While this works find on a smaller scale, for large scale complex services this starts becoming difficult to manage and having a DI based API surface could make things much simpler. Apart from the fact that DI would improve the testability of the code, it will also allow for better management of creation of Meter object in a consistent fashion. With DI based approach a meter can be consistently created with the type name of the class where the meter is injected, which opens up a lot of possibilities for further extensions that could simplify the programming model.
We have a metrics solution that our teams uses. When we implemented the solution .NET metrics API was not in existence so we had created our own API surface for metrics. We introduced DI friendly IMeter and IMeter which works similar to ILogger and ILogger. Over the time we found the DI friendly surface extremely useful and extensible, it turned out to be super easy for services and has allowed us to have a consistent approach of creating meter object everywhere. Service owners and library owners don't need to worry about cooking up names for the meter object and the meter object automatically gets created with consistent naming. This allows us to add various capabilities by providing filtering based on the meter names via config. Few examples of the capabilities
- Services can configure the state of individual meters via config (i.e. enable/disable a meter by configuring the metering state in their appsettings.json using the type name of namespace, similar to how one can configure logging levels with .NET ILogger)
- Services can configure different destinations for metrics generated by different meter objects. This works even when using third party libraries seamlessly as long as the libraries are using DI to inject meter. etc.
Modern .NET services use DI heavily due to it's benefits and the trend will only increase going forward. Based on our experience with IMeter API and the feedback of simplicity from our customers, we think it would be highly useful for the rest of the community too.
API Proposal
namespace System.Diagnostics.Metrics;
public interface IMeter
{
}
public interface IMeter<out TCategoryName> : IMeter
{
}OR
namespace System.Diagnostics.Metrics;
public class Meter<out TCategoryName>
{
}API Usage
public class MyClass
{
// Inject Meter<T> object using DI
public MyClass(IMeter<MyClass> meter)
{
var counter = meter.CreateCounter<long>("counter1");
}
}
public class AnotherClass
{
// Inject a meter with the full name of the provided T gets injected using DI.
public AnotherClass(IMeter<AnotherClass> meter)
{
var counter = meter.CreateCounter<long>("counter2");
}
}Alternative Designs
The alternative is to write a custom DI wrapper for Meter and introduce Meter in a wrapper which then defeats the purpose of exposing the Meter API exposed from .NET directly.
Risks
It's a new addition to existing APIs so shouldn't cause breaking changes.
Activity
julealgon commentedon Dec 16, 2022
This part turned me off.
The same pattern is used with
ILoggerand I see it more as a workaround to lack of injection target inspection in the container itself. If you look at theILogger<T>type, it "does nothing", it's basically a marker interface to differentiate registrations in the container: again, a workaround.Instead of expanding on that (IMHO terrible) practice, I'd rather see something similar to how
HttpClientis handled today. It suffers from similar issues, but they were solved without "hurting" the type itself:HttpClientremains non-generic, but there are injection helpers that facilitate associating a givenHttpClientwith the service that is going to consume it.Now... don't get me wrong: I still think even the
AddHttpClientmethods are also hacky workarounds to the underlying root problem here which is an inability of inspecting the target injection type during dependency injection. It would be nice to have that as it would allow you to have all these patterns without dedicated container extensions, but that's probably a separate discussion altogether.Lastly, about this:
I'm not very fond of having instrument creation happening inside my classes either. In all scenarios where I've used custom metrics, I've always made sure to configure and set them all up in the container, and inject the counters. Consumers shouldn't have to know how to create the counters (and gauges, and other instruments); they should only use them.
On that front, what I've also done is extract a
ICounter<T>interface for my own purposes, and test around that.If this proposal is seriously taken into consideration, I'd also recommend potentially extracting common interfaces for the instruments themselves as they are, IMHO, the core of the untestability in regards to metrics classes.
tarekgh commentedon Dec 17, 2022
Thanks @julealgon for the feedback, it is helpful. We'll look at this at some point next year. I am wondering if you have any specific proposal that you think addresses the request in the proper way.
julealgon commentedon Dec 20, 2022
That's good to hear. This API is indeed extremely unfriendly to modern patterns using Extensions.Hosting.
Aside from providing an interface to each instrument type, I think this entire namespace needs a companion "Extensions.Hosting" extension with methods to add metrics and instruments to the container. In a sense, this approach wouldn't be too far off from what Azure and OTEL provide with their
Microsoft.Extensions.AzureandOpenTelemetry.Extensions.Hostingrespectively.As for the API, I could see very similar needs to what the various
AddHttpClientextensions provide:I{Instrument}Factoryanalogous toIHttpClientFactory)As well as some stuff that would have to be thought from scratch I think:
Meterinstances to the container along with their instrumentsAs part of this work, I'd also like to see better integration with OTEL itself, so that one doesn't need to pass strings around to indicate the meters to track etc. Maybe add some method in the OTEL extensions that just "honors all meters defined in the container automatically" (that's what would make the most sense in my use cases).
Lastly, I just want to emphasize again how hard and convoluted it is to create some of these container-related extensions, and that is mostly due to restrictions on what the MS container keeps track of. It would be really nice if MS reconsidered the feature-set it provides out of the native container, so that things such as "named/keyed registrations" and "target-based injection decisions" were possible natively (especially the latter).
For reference, I'll drop one of our more advanced usages here (should help people understand where I'm coming from). Things have been renamed/simplified from the actual code:
Notes about this implementation:
CustomStuffAvailabilityReportingContextis used as an "ambient" storage to communicate a hosted service with an ObservableGauge.InstanceInitializerServiceis there to "force" initialization of the gauge (I wish I didn't have to do this, but the gauge only starts when it is first resolved from the container of course...)AddNamedSingletonis our custom extension to register named instances in the container (usingLazy<T, TMetadata>internally). Obviously wish this had a native counterpart but there is noneCreateUpDownCounterOfIntis just a .NET6 workaround forUpDownCountersupport (creates a customICounterimplementation that uses 2 counters internally: one to represent increments, and another to represent decrements). This is going away now that we've migrated to .NET7 and can use the actualUpDownCounterinstrumentAdaptToICounteris a custom extension that returns an adapter that implements our customICounterinterface (abstraction to enable proper testing)StuffTrackerrelies on 3 counters and updates them depending on some methods that are called on it. This is where being able to inject multiple instruments in the same target service would be usefulDecorateis just usingScrutorto add a few decorators to some of our existing command handlers (MediatR), so that we can update the 3 counters depending on what actions are performedOur initial implementation only contained the 3 counters. The ObservableGauge + Hosted Service were added later as another workaround: they will be removed soon.
Of note as well, is how unfriendly to DI the
ObservableGaugeAPI is... the whole thing about passing a container-controlled state object from the gauge to the service was really hard to get right, especially with having to force initialization of the gauge separately.tekian commentedon Jan 27, 2023
This is very problematic.
Whenever a new meter is created, a static (i.e., application-wide) meter list under lock is modified.
It should be noted that metering is typically being used to create business counters and custom metrics across services. Being able to test the counters - values and dimensions - is paramount.
I don't think counters should be declared upfront as per @julealgon's example because why should a consumer of a library need to know how counters are named, aggregated or what's the unit. And if I own the feature, why would I want them to unfold into DI? Quite contrary. Whoever writes the feature has all the knowledge to make the right call on how should the metrics be named, structured, aggregated and used.
I believe it would be enough to provide an abstract
MeterFactorywithCreateMeter()method. Inside my class, I would then create all the counters that I need, details of which are cohesively part of the class that uses them. But the major difference is that now I can test this. I can provideMockMeterFactoryand assert any values I need.The real implementation of
MeterFactorywould new-upMeter, registering it with the static collection (still yuck!).51 remaining items
JamesNK commentedon May 18, 2023
Yeah, I saw the flag. That's a good improvement.
If you think docs are enough to explain the potential danger of this type then ok. Just want to double check it's been thought about.
JamesNK commentedon May 18, 2023
I worry about future new parameters that a
Metermight take. We've just added tags. There may be new parameters in the future. An interface is difficult to version.Have you considered the
Createmethod taking an options class? For example:Future parameters can easily be added to the options class. Then either have an overload with these parameters or an extension method that calls the
IMeterFactory.Create(MeterOptions options)method. Meters aren't created often so the overhead of allocatingMeterOptionsisn't important.noahfalk commentedon May 18, 2023
@tarekgh - Is the door still open to incorporate James' MeterOptions feedback? It feels pretty reasonable to me and it was something I was worrying about recently as in the future OpenTelemetry might want to add another constructor parameter like SchemaUrl. Perhaps specifically:
The extension method could preserve the current suggested use in code as-is but still leaves the door open to non-breaking additions in the future.
tarekgh commentedon May 18, 2023
@noahfalk @JamesNK
The suggestions sound reasonable to me. One thing I'll add to the
MeterOptionsis theScope. I'll edit @noahfalk proposal to accommodate that too.Delta changes from last approved
We are changing
Contextname toScope.InstrumentRecorder.Instrumentto return nullable value. e.g.,Instrument?.bartonjs commentedon May 18, 2023
Video
vandre commentedon Jun 17, 2023
How would I use IMetricsFactory with Azure Monitor? Is there a reference implementation?
tarekgh commentedon Jun 17, 2023
The new .NET 8.0 preview libraries having the new APIs are not released yet to NuGet but should happen soon. You may look at dotnet/core#8436 (comment) for info. The new APIs are going to be released in libraries called
Microsoft.Extensions.Diagnostics.AbstractionsandMicrosoft.Extensions.Diagnostics.