Fix IDE0090: 'new' expression can be simplified. (#3012)

* Set rule for new() usage.

* Fix IDE0090 "'new' expression can be simplified"
This commit is contained in:
Travis Illig 2022-03-10 08:57:53 -08:00 committed by GitHub
parent 7b19794de3
commit 2a97920ff0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
108 changed files with 183 additions and 182 deletions

View File

@ -65,6 +65,7 @@ csharp_prefer_braces = true:silent
csharp_preserve_single_line_blocks = true csharp_preserve_single_line_blocks = true
csharp_preserve_single_line_statements = true csharp_preserve_single_line_statements = true
dotnet_style_readonly_field = true:suggestion dotnet_style_readonly_field = true:suggestion
csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion
# Expression-level preferences # Expression-level preferences
dotnet_style_object_initializer = true:suggestion dotnet_style_object_initializer = true:suggestion

View File

@ -21,8 +21,8 @@ using OpenTelemetry.Metrics;
public class Program public class Program
{ {
private static readonly Meter Meter1 = new Meter("CompanyA.ProductA.Library1", "1.0"); private static readonly Meter Meter1 = new("CompanyA.ProductA.Library1", "1.0");
private static readonly Meter Meter2 = new Meter("CompanyA.ProductB.Library2", "1.0"); private static readonly Meter Meter2 = new("CompanyA.ProductB.Library2", "1.0");
public static void Main(string[] args) public static void Main(string[] args)
{ {

View File

@ -23,7 +23,7 @@ using OpenTelemetry.Metrics;
public class Program public class Program
{ {
private static readonly Meter MyMeter = new Meter("MyCompany.MyProduct.MyLibrary", "1.0"); private static readonly Meter MyMeter = new("MyCompany.MyProduct.MyLibrary", "1.0");
private static readonly Counter<long> MyFruitCounter = MyMeter.CreateCounter<long>("MyFruitCounter"); private static readonly Counter<long> MyFruitCounter = MyMeter.CreateCounter<long>("MyFruitCounter");
static Program() static Program()

View File

@ -22,7 +22,7 @@ using OpenTelemetry.Metrics;
public class Program public class Program
{ {
private static readonly Meter MyMeter = new Meter("MyCompany.MyProduct.MyLibrary", "1.0"); private static readonly Meter MyMeter = new("MyCompany.MyProduct.MyLibrary", "1.0");
private static readonly Counter<long> MyFruitCounter = MyMeter.CreateCounter<long>("MyFruitCounter"); private static readonly Counter<long> MyFruitCounter = MyMeter.CreateCounter<long>("MyFruitCounter");
public static void Main(string[] args) public static void Main(string[] args)

View File

@ -20,7 +20,7 @@ using OpenTelemetry.Metrics;
public class Program public class Program
{ {
private static readonly Meter MyMeter = new Meter("MyCompany.MyProduct.MyLibrary", "1.0"); private static readonly Meter MyMeter = new("MyCompany.MyProduct.MyLibrary", "1.0");
private static readonly Counter<long> MyFruitCounter = MyMeter.CreateCounter<long>("MyFruitCounter"); private static readonly Counter<long> MyFruitCounter = MyMeter.CreateCounter<long>("MyFruitCounter");
public static void Main(string[] args) public static void Main(string[] args)

View File

@ -23,7 +23,7 @@ using OpenTelemetry.Metrics;
public class Program public class Program
{ {
private static readonly Meter MyMeter = new Meter("MyCompany.MyProduct.MyLibrary", "1.0"); private static readonly Meter MyMeter = new("MyCompany.MyProduct.MyLibrary", "1.0");
private static readonly Histogram<long> MyHistogram = MyMeter.CreateHistogram<long>("MyHistogram"); private static readonly Histogram<long> MyHistogram = MyMeter.CreateHistogram<long>("MyHistogram");
static Program() static Program()

View File

@ -20,16 +20,16 @@ using OpenTelemetry.Trace;
public class Program public class Program
{ {
private static readonly ActivitySource MyLibraryActivitySource = new ActivitySource( private static readonly ActivitySource MyLibraryActivitySource = new(
"MyCompany.MyProduct.MyLibrary"); "MyCompany.MyProduct.MyLibrary");
private static readonly ActivitySource ComponentAActivitySource = new ActivitySource( private static readonly ActivitySource ComponentAActivitySource = new(
"AbcCompany.XyzProduct.ComponentA"); "AbcCompany.XyzProduct.ComponentA");
private static readonly ActivitySource ComponentBActivitySource = new ActivitySource( private static readonly ActivitySource ComponentBActivitySource = new(
"AbcCompany.XyzProduct.ComponentB"); "AbcCompany.XyzProduct.ComponentB");
private static readonly ActivitySource SomeOtherActivitySource = new ActivitySource( private static readonly ActivitySource SomeOtherActivitySource = new(
"SomeCompany.SomeProduct.SomeComponent"); "SomeCompany.SomeProduct.SomeComponent");
public static void Main() public static void Main()

View File

@ -21,7 +21,7 @@ using OpenTelemetry.Trace;
public class Program public class Program
{ {
private static readonly ActivitySource DemoSource = new ActivitySource("OTel.Demo"); private static readonly ActivitySource DemoSource = new("OTel.Demo");
public static void Main() public static void Main()
{ {

View File

@ -20,7 +20,7 @@ using OpenTelemetry.Trace;
public class Program public class Program
{ {
private static readonly ActivitySource MyActivitySource = new ActivitySource( private static readonly ActivitySource MyActivitySource = new(
"MyCompany.MyProduct.MyLibrary"); "MyCompany.MyProduct.MyLibrary");
public static void Main() public static void Main()

View File

@ -21,7 +21,7 @@ using OpenTelemetry.Trace;
public class Program public class Program
{ {
private static readonly ActivitySource MyActivitySource = new ActivitySource( private static readonly ActivitySource MyActivitySource = new(
"MyCompany.MyProduct.MyLibrary"); "MyCompany.MyProduct.MyLibrary");
public static void Main() public static void Main()

View File

@ -33,7 +33,7 @@ namespace Examples.AspNetCore.Controllers
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching", "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching",
}; };
private static readonly HttpClient HttpClient = new HttpClient(); private static readonly HttpClient HttpClient = new();
private readonly ILogger<WeatherForecastController> logger; private readonly ILogger<WeatherForecastController> logger;

View File

@ -30,8 +30,8 @@ namespace Examples.Console
internal class InstrumentationWithActivitySource : IDisposable internal class InstrumentationWithActivitySource : IDisposable
{ {
private const string RequestPath = "/api/request"; private const string RequestPath = "/api/request";
private readonly SampleServer server = new SampleServer(); private readonly SampleServer server = new();
private readonly SampleClient client = new SampleClient(); private readonly SampleClient client = new();
public void Start(ushort port = 19999) public void Start(ushort port = 19999)
{ {
@ -48,7 +48,7 @@ namespace Examples.Console
private class SampleServer : IDisposable private class SampleServer : IDisposable
{ {
private readonly HttpListener listener = new HttpListener(); private readonly HttpListener listener = new();
public void Start(string url) public void Start(string url)
{ {

View File

@ -28,11 +28,11 @@ namespace Examples.Console;
internal class TestPrometheusExporter internal class TestPrometheusExporter
{ {
private static readonly Meter MyMeter = new Meter("MyMeter"); private static readonly Meter MyMeter = new("MyMeter");
private static readonly Meter MyMeter2 = new Meter("MyMeter2"); private static readonly Meter MyMeter2 = new("MyMeter2");
private static readonly Counter<double> Counter = MyMeter.CreateCounter<double>("myCounter", description: "A counter for demonstration purpose."); private static readonly Counter<double> Counter = MyMeter.CreateCounter<double>("myCounter", description: "A counter for demonstration purpose.");
private static readonly Histogram<long> MyHistogram = MyMeter.CreateHistogram<long>("myHistogram"); private static readonly Histogram<long> MyHistogram = MyMeter.CreateHistogram<long>("myHistogram");
private static readonly ThreadLocal<Random> ThreadLocalRandom = new ThreadLocal<Random>(() => new Random()); private static readonly ThreadLocal<Random> ThreadLocalRandom = new(() => new Random());
internal static object Run(int port) internal static object Run(int port)
{ {

View File

@ -30,7 +30,7 @@ namespace Utils.Messaging
{ {
public class MessageReceiver : IDisposable public class MessageReceiver : IDisposable
{ {
private static readonly ActivitySource ActivitySource = new ActivitySource(nameof(MessageReceiver)); private static readonly ActivitySource ActivitySource = new(nameof(MessageReceiver));
private static readonly TextMapPropagator Propagator = Propagators.DefaultTextMapPropagator; private static readonly TextMapPropagator Propagator = Propagators.DefaultTextMapPropagator;
private readonly ILogger<MessageReceiver> logger; private readonly ILogger<MessageReceiver> logger;

View File

@ -27,7 +27,7 @@ namespace Utils.Messaging
{ {
public class MessageSender : IDisposable public class MessageSender : IDisposable
{ {
private static readonly ActivitySource ActivitySource = new ActivitySource(nameof(MessageSender)); private static readonly ActivitySource ActivitySource = new(nameof(MessageSender));
private static readonly TextMapPropagator Propagator = Propagators.DefaultTextMapPropagator; private static readonly TextMapPropagator Propagator = Propagators.DefaultTextMapPropagator;
private readonly ILogger<MessageSender> logger; private readonly ILogger<MessageSender> logger;

View File

@ -31,7 +31,7 @@ namespace OpenTelemetry
public readonly struct Baggage : IEquatable<Baggage> public readonly struct Baggage : IEquatable<Baggage>
{ {
private static readonly RuntimeContextSlot<BaggageHolder> RuntimeContextSlot = RuntimeContext.RegisterSlot<BaggageHolder>("otel.baggage"); private static readonly RuntimeContextSlot<BaggageHolder> RuntimeContextSlot = RuntimeContext.RegisterSlot<BaggageHolder>("otel.baggage");
private static readonly Dictionary<string, string> EmptyBaggage = new Dictionary<string, string>(); private static readonly Dictionary<string, string> EmptyBaggage = new();
private readonly Dictionary<string, string> baggage; private readonly Dictionary<string, string> baggage;

View File

@ -49,9 +49,9 @@ namespace OpenTelemetry.Context.Propagation
// "Debug" sampled value. // "Debug" sampled value.
internal const string FlagsValue = "1"; internal const string FlagsValue = "1";
private static readonly HashSet<string> AllFields = new HashSet<string>() { XB3TraceId, XB3SpanId, XB3ParentSpanId, XB3Sampled, XB3Flags }; private static readonly HashSet<string> AllFields = new() { XB3TraceId, XB3SpanId, XB3ParentSpanId, XB3Sampled, XB3Flags };
private static readonly HashSet<string> SampledValues = new HashSet<string>(StringComparer.Ordinal) { SampledValue, LegacySampledValue }; private static readonly HashSet<string> SampledValues = new(StringComparer.Ordinal) { SampledValue, LegacySampledValue };
private readonly bool singleHeader; private readonly bool singleHeader;

View File

@ -26,7 +26,7 @@ namespace OpenTelemetry.Context
/// </summary> /// </summary>
public static class RuntimeContext public static class RuntimeContext
{ {
private static readonly ConcurrentDictionary<string, object> Slots = new ConcurrentDictionary<string, object>(); private static readonly ConcurrentDictionary<string, object> Slots = new();
/// <summary> /// <summary>
/// Gets or sets the actual context carrier implementation. /// Gets or sets the actual context carrier implementation.

View File

@ -26,7 +26,7 @@ namespace OpenTelemetry.Internal
[EventSource(Name = "OpenTelemetry-Api")] [EventSource(Name = "OpenTelemetry-Api")]
internal class OpenTelemetryApiEventSource : EventSource internal class OpenTelemetryApiEventSource : EventSource
{ {
public static OpenTelemetryApiEventSource Log = new OpenTelemetryApiEventSource(); public static OpenTelemetryApiEventSource Log = new();
[NonEvent] [NonEvent]
public void ActivityContextExtractException(string format, Exception ex) public void ActivityContextExtractException(string format, Exception ex)

View File

@ -24,17 +24,17 @@ namespace OpenTelemetry.Trace
/// <summary> /// <summary>
/// The operation completed successfully. /// The operation completed successfully.
/// </summary> /// </summary>
public static readonly Status Ok = new Status(StatusCode.Ok); public static readonly Status Ok = new(StatusCode.Ok);
/// <summary> /// <summary>
/// The default status. /// The default status.
/// </summary> /// </summary>
public static readonly Status Unset = new Status(StatusCode.Unset); public static readonly Status Unset = new(StatusCode.Unset);
/// <summary> /// <summary>
/// The operation contains an error. /// The operation contains an error.
/// </summary> /// </summary>
public static readonly Status Error = new Status(StatusCode.Error); public static readonly Status Error = new(StatusCode.Error);
internal Status(StatusCode statusCode, string description = null) internal Status(StatusCode statusCode, string description = null)
{ {

View File

@ -27,7 +27,7 @@ namespace OpenTelemetry.Trace
/// <remarks>TelemetrySpan is a wrapper around <see cref="Activity"/> class.</remarks> /// <remarks>TelemetrySpan is a wrapper around <see cref="Activity"/> class.</remarks>
public class TelemetrySpan : IDisposable public class TelemetrySpan : IDisposable
{ {
internal static readonly TelemetrySpan NoopInstance = new TelemetrySpan(null); internal static readonly TelemetrySpan NoopInstance = new(null);
internal readonly Activity Activity; internal readonly Activity Activity;
internal TelemetrySpan(Activity activity) internal TelemetrySpan(Activity activity)

View File

@ -26,7 +26,7 @@ namespace OpenTelemetry.Exporter.Jaeger.Implementation
[EventSource(Name = "OpenTelemetry-Exporter-Jaeger")] [EventSource(Name = "OpenTelemetry-Exporter-Jaeger")]
internal class JaegerExporterEventSource : EventSource internal class JaegerExporterEventSource : EventSource
{ {
public static JaegerExporterEventSource Log = new JaegerExporterEventSource(); public static JaegerExporterEventSource Log = new();
[NonEvent] [NonEvent]
public void FailedExport(Exception ex) public void FailedExport(Exception ex)

View File

@ -23,7 +23,7 @@ namespace OpenTelemetry.Exporter.Jaeger.Implementation
{ {
internal sealed class JaegerHttpClient : IJaegerClient internal sealed class JaegerHttpClient : IJaegerClient
{ {
private static readonly MediaTypeHeaderValue ContentTypeHeader = new MediaTypeHeaderValue("application/vnd.apache.thrift.binary"); private static readonly MediaTypeHeaderValue ContentTypeHeader = new("application/vnd.apache.thrift.binary");
private readonly Uri endpoint; private readonly Uri endpoint;
private readonly HttpClient httpClient; private readonly HttpClient httpClient;

View File

@ -35,7 +35,7 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
{ {
internal static class ActivityExtensions internal static class ActivityExtensions
{ {
private static readonly ConcurrentBag<OtlpTrace.InstrumentationLibrarySpans> SpanListPool = new ConcurrentBag<OtlpTrace.InstrumentationLibrarySpans>(); private static readonly ConcurrentBag<OtlpTrace.InstrumentationLibrarySpans> SpanListPool = new();
private static readonly Action<RepeatedField<OtlpTrace.Span>, int> RepeatedFieldOfSpanSetCountAction = CreateRepeatedFieldOfSpanSetCountAction(); private static readonly Action<RepeatedField<OtlpTrace.Span>, int> RepeatedFieldOfSpanSetCountAction = CreateRepeatedFieldOfSpanSetCountAction();
internal static void AddBatch( internal static void AddBatch(

View File

@ -56,7 +56,7 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation.ExportClie
internal sealed class ExportRequestContent : HttpContent internal sealed class ExportRequestContent : HttpContent
{ {
private static readonly MediaTypeHeaderValue ProtobufMediaTypeHeader = new MediaTypeHeaderValue(MediaContentType); private static readonly MediaTypeHeaderValue ProtobufMediaTypeHeader = new(MediaContentType);
private readonly OtlpCollector.ExportMetricsServiceRequest exportRequest; private readonly OtlpCollector.ExportMetricsServiceRequest exportRequest;

View File

@ -56,7 +56,7 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation.ExportClie
internal sealed class ExportRequestContent : HttpContent internal sealed class ExportRequestContent : HttpContent
{ {
private static readonly MediaTypeHeaderValue ProtobufMediaTypeHeader = new MediaTypeHeaderValue(MediaContentType); private static readonly MediaTypeHeaderValue ProtobufMediaTypeHeader = new(MediaContentType);
private readonly OtlpCollector.ExportTraceServiceRequest exportRequest; private readonly OtlpCollector.ExportTraceServiceRequest exportRequest;

View File

@ -32,7 +32,7 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
{ {
internal static class MetricItemExtensions internal static class MetricItemExtensions
{ {
private static readonly ConcurrentBag<OtlpMetrics.InstrumentationLibraryMetrics> MetricListPool = new ConcurrentBag<OtlpMetrics.InstrumentationLibraryMetrics>(); private static readonly ConcurrentBag<OtlpMetrics.InstrumentationLibraryMetrics> MetricListPool = new();
private static readonly Action<RepeatedField<OtlpMetrics.Metric>, int> RepeatedFieldOfMetricSetCountAction = CreateRepeatedFieldOfMetricSetCountAction(); private static readonly Action<RepeatedField<OtlpMetrics.Metric>, int> RepeatedFieldOfMetricSetCountAction = CreateRepeatedFieldOfMetricSetCountAction();
internal static void AddMetrics( internal static void AddMetrics(

View File

@ -23,7 +23,7 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
[EventSource(Name = "OpenTelemetry-Exporter-OpenTelemetryProtocol")] [EventSource(Name = "OpenTelemetry-Exporter-OpenTelemetryProtocol")]
internal class OpenTelemetryProtocolExporterEventSource : EventSource internal class OpenTelemetryProtocolExporterEventSource : EventSource
{ {
public static readonly OpenTelemetryProtocolExporterEventSource Log = new OpenTelemetryProtocolExporterEventSource(); public static readonly OpenTelemetryProtocolExporterEventSource Log = new();
[NonEvent] [NonEvent]
public void FailedToReachCollector(Uri collectorUri, Exception ex) public void FailedToReachCollector(Uri collectorUri, Exception ex)

View File

@ -26,7 +26,7 @@ namespace OpenTelemetry.Exporter.Prometheus
[EventSource(Name = "OpenTelemetry-Exporter-Prometheus")] [EventSource(Name = "OpenTelemetry-Exporter-Prometheus")]
internal sealed class PrometheusExporterEventSource : EventSource internal sealed class PrometheusExporterEventSource : EventSource
{ {
public static PrometheusExporterEventSource Log = new PrometheusExporterEventSource(); public static PrometheusExporterEventSource Log = new();
[NonEvent] [NonEvent]
public void FailedExport(Exception ex) public void FailedExport(Exception ex)

View File

@ -28,8 +28,8 @@ namespace OpenTelemetry.Exporter.Prometheus
internal sealed class PrometheusExporterHttpServer : IDisposable internal sealed class PrometheusExporterHttpServer : IDisposable
{ {
private readonly PrometheusExporter exporter; private readonly PrometheusExporter exporter;
private readonly HttpListener httpListener = new HttpListener(); private readonly HttpListener httpListener = new();
private readonly object syncObject = new object(); private readonly object syncObject = new();
private CancellationTokenSource tokenSource; private CancellationTokenSource tokenSource;
private Task workerThread; private Task workerThread;

View File

@ -26,7 +26,7 @@ namespace OpenTelemetry.Exporter.ZPages.Implementation
[EventSource(Name = "OpenTelemetry-Exporter-ZPages")] [EventSource(Name = "OpenTelemetry-Exporter-ZPages")]
internal class ZPagesExporterEventSource : EventSource internal class ZPagesExporterEventSource : EventSource
{ {
public static ZPagesExporterEventSource Log = new ZPagesExporterEventSource(); public static ZPagesExporterEventSource Log = new();
[NonEvent] [NonEvent]
public void FailedExport(Exception ex) public void FailedExport(Exception ex)

View File

@ -30,8 +30,8 @@ namespace OpenTelemetry.Exporter.ZPages
/// </summary> /// </summary>
public class ZPagesExporterStatsHttpServer : IDisposable public class ZPagesExporterStatsHttpServer : IDisposable
{ {
private readonly HttpListener httpListener = new HttpListener(); private readonly HttpListener httpListener = new();
private readonly object syncObject = new object(); private readonly object syncObject = new();
private CancellationTokenSource tokenSource; private CancellationTokenSource tokenSource;
private Task workerThread; private Task workerThread;

View File

@ -30,7 +30,7 @@ namespace OpenTelemetry.Exporter.Zipkin.Implementation
private const long UnixEpochTicks = 621355968000000000L; // = DateTimeOffset.FromUnixTimeMilliseconds(0).Ticks private const long UnixEpochTicks = 621355968000000000L; // = DateTimeOffset.FromUnixTimeMilliseconds(0).Ticks
private const long UnixEpochMicroseconds = UnixEpochTicks / TicksPerMicrosecond; private const long UnixEpochMicroseconds = UnixEpochTicks / TicksPerMicrosecond;
private static readonly ConcurrentDictionary<(string, int), ZipkinEndpoint> RemoteEndpointCache = new ConcurrentDictionary<(string, int), ZipkinEndpoint>(); private static readonly ConcurrentDictionary<(string, int), ZipkinEndpoint> RemoteEndpointCache = new();
internal static ZipkinSpan ToZipkinSpan(this Activity activity, ZipkinEndpoint localEndpoint, bool useShortTraceIds = false) internal static ZipkinSpan ToZipkinSpan(this Activity activity, ZipkinEndpoint localEndpoint, bool useShortTraceIds = false)
{ {

View File

@ -26,7 +26,7 @@ namespace OpenTelemetry.Exporter.Zipkin.Implementation
[EventSource(Name = "OpenTelemetry-Exporter-Zipkin")] [EventSource(Name = "OpenTelemetry-Exporter-Zipkin")]
internal class ZipkinExporterEventSource : EventSource internal class ZipkinExporterEventSource : EventSource
{ {
public static ZipkinExporterEventSource Log = new ZipkinExporterEventSource(); public static ZipkinExporterEventSource Log = new();
[NonEvent] [NonEvent]
public void FailedExport(Exception ex) public void FailedExport(Exception ex)

View File

@ -189,7 +189,7 @@ namespace OpenTelemetry.Exporter
private sealed class JsonContent : HttpContent private sealed class JsonContent : HttpContent
{ {
private static readonly MediaTypeHeaderValue JsonHeader = new MediaTypeHeaderValue("application/json") private static readonly MediaTypeHeaderValue JsonHeader = new("application/json")
{ {
CharSet = "utf-8", CharSet = "utf-8",
}; };

View File

@ -26,7 +26,7 @@ namespace OpenTelemetry.Extensions.Hosting.Implementation
[EventSource(Name = "OpenTelemetry-Extensions-Hosting")] [EventSource(Name = "OpenTelemetry-Extensions-Hosting")]
internal class HostingExtensionsEventSource : EventSource internal class HostingExtensionsEventSource : EventSource
{ {
public static HostingExtensionsEventSource Log = new HostingExtensionsEventSource(); public static HostingExtensionsEventSource Log = new();
[NonEvent] [NonEvent]
public void FailedInitialize(Exception ex) public void FailedInitialize(Exception ex)

View File

@ -26,7 +26,7 @@ namespace OpenTelemetry.Metrics
/// </summary> /// </summary>
internal sealed class MeterProviderBuilderHosting : MeterProviderBuilderBase, IDeferredMeterProviderBuilder internal sealed class MeterProviderBuilderHosting : MeterProviderBuilderBase, IDeferredMeterProviderBuilder
{ {
private readonly List<Action<IServiceProvider, MeterProviderBuilder>> configurationActions = new List<Action<IServiceProvider, MeterProviderBuilder>>(); private readonly List<Action<IServiceProvider, MeterProviderBuilder>> configurationActions = new();
public MeterProviderBuilderHosting(IServiceCollection services) public MeterProviderBuilderHosting(IServiceCollection services)
{ {

View File

@ -26,7 +26,7 @@ namespace OpenTelemetry.Trace
/// </summary> /// </summary>
internal sealed class TracerProviderBuilderHosting : TracerProviderBuilderBase, IDeferredTracerProviderBuilder internal sealed class TracerProviderBuilderHosting : TracerProviderBuilderBase, IDeferredTracerProviderBuilder
{ {
private readonly List<Action<IServiceProvider, TracerProviderBuilder>> configurationActions = new List<Action<IServiceProvider, TracerProviderBuilder>>(); private readonly List<Action<IServiceProvider, TracerProviderBuilder>> configurationActions = new();
public TracerProviderBuilderHosting(IServiceCollection services) public TracerProviderBuilderHosting(IServiceCollection services)
{ {

View File

@ -33,11 +33,11 @@ namespace OpenTelemetry.Instrumentation.AspNet
/// Key to store the state in HttpContext. /// Key to store the state in HttpContext.
/// </summary> /// </summary>
internal const string ContextKey = "__AspnetInstrumentationContext__"; internal const string ContextKey = "__AspnetInstrumentationContext__";
internal static readonly object StartedButNotSampledObj = new object(); internal static readonly object StartedButNotSampledObj = new();
private const string BaggageSlotName = "otel.baggage"; private const string BaggageSlotName = "otel.baggage";
private static readonly Func<HttpRequest, string, IEnumerable<string>> HttpRequestHeaderValuesGetter = (request, name) => request.Headers.GetValues(name); private static readonly Func<HttpRequest, string, IEnumerable<string>> HttpRequestHeaderValuesGetter = (request, name) => request.Headers.GetValues(name);
private static readonly ActivitySource AspNetSource = new ActivitySource( private static readonly ActivitySource AspNetSource = new(
TelemetryHttpModule.AspNetSourceName, TelemetryHttpModule.AspNetSourceName,
typeof(ActivityHelper).Assembly.GetName().Version.ToString()); typeof(ActivityHelper).Assembly.GetName().Version.ToString());

View File

@ -30,7 +30,7 @@ namespace OpenTelemetry.Instrumentation.AspNet
/// <summary> /// <summary>
/// Instance of the PlatformEventSource class. /// Instance of the PlatformEventSource class.
/// </summary> /// </summary>
public static readonly AspNetTelemetryEventSource Log = new AspNetTelemetryEventSource(); public static readonly AspNetTelemetryEventSource Log = new();
[NonEvent] [NonEvent]
public void ActivityStarted(Activity activity) public void ActivityStarted(Activity activity)

View File

@ -26,7 +26,7 @@ namespace OpenTelemetry.Instrumentation.AspNet.Implementation
[EventSource(Name = "OpenTelemetry-Instrumentation-AspNet")] [EventSource(Name = "OpenTelemetry-Instrumentation-AspNet")]
internal sealed class AspNetInstrumentationEventSource : EventSource internal sealed class AspNetInstrumentationEventSource : EventSource
{ {
public static AspNetInstrumentationEventSource Log = new AspNetInstrumentationEventSource(); public static AspNetInstrumentationEventSource Log = new();
[NonEvent] [NonEvent]
public void RequestFilterException(string operationName, Exception ex) public void RequestFilterException(string operationName, Exception ex)

View File

@ -26,7 +26,7 @@ namespace OpenTelemetry.Instrumentation.AspNetCore.Implementation
[EventSource(Name = "OpenTelemetry-Instrumentation-AspNetCore")] [EventSource(Name = "OpenTelemetry-Instrumentation-AspNetCore")]
internal class AspNetCoreInstrumentationEventSource : EventSource internal class AspNetCoreInstrumentationEventSource : EventSource
{ {
public static AspNetCoreInstrumentationEventSource Log = new AspNetCoreInstrumentationEventSource(); public static AspNetCoreInstrumentationEventSource Log = new();
[NonEvent] [NonEvent]
public void RequestFilterException(Exception ex) public void RequestFilterException(Exception ex)

View File

@ -38,7 +38,7 @@ namespace OpenTelemetry.Instrumentation.AspNetCore.Implementation
internal static readonly AssemblyName AssemblyName = typeof(HttpInListener).Assembly.GetName(); internal static readonly AssemblyName AssemblyName = typeof(HttpInListener).Assembly.GetName();
internal static readonly string ActivitySourceName = AssemblyName.Name; internal static readonly string ActivitySourceName = AssemblyName.Name;
internal static readonly Version Version = AssemblyName.Version; internal static readonly Version Version = AssemblyName.Version;
internal static readonly ActivitySource ActivitySource = new ActivitySource(ActivitySourceName, Version.ToString()); internal static readonly ActivitySource ActivitySource = new(ActivitySourceName, Version.ToString());
private const string DiagnosticSourceName = "Microsoft.AspNetCore"; private const string DiagnosticSourceName = "Microsoft.AspNetCore";
private const string UnknownHostName = "UNKNOWN-HOST"; private const string UnknownHostName = "UNKNOWN-HOST";
private static readonly Func<HttpRequest, string, IEnumerable<string>> HttpRequestHeaderValuesGetter = (request, name) => request.Headers[name]; private static readonly Func<HttpRequest, string, IEnumerable<string>> HttpRequestHeaderValuesGetter = (request, name) => request.Headers[name];

View File

@ -23,7 +23,7 @@ namespace OpenTelemetry.Instrumentation.AspNetCore.Implementation
{ {
internal class HttpInMetricsListener : ListenerHandler internal class HttpInMetricsListener : ListenerHandler
{ {
private readonly PropertyFetcher<HttpContext> stopContextFetcher = new PropertyFetcher<HttpContext>("HttpContext"); private readonly PropertyFetcher<HttpContext> stopContextFetcher = new("HttpContext");
private readonly Meter meter; private readonly Meter meter;
private readonly Histogram<double> httpServerDuration; private readonly Histogram<double> httpServerDuration;

View File

@ -29,7 +29,7 @@ namespace OpenTelemetry.Instrumentation.GrpcNetClient
public const string GrpcMethodTagName = "grpc.method"; public const string GrpcMethodTagName = "grpc.method";
public const string GrpcStatusCodeTagName = "grpc.status_code"; public const string GrpcStatusCodeTagName = "grpc.status_code";
private static readonly Regex GrpcMethodRegex = new Regex(@"^/?(?<service>.*)/(?<method>.*)$", RegexOptions.Compiled); private static readonly Regex GrpcMethodRegex = new(@"^/?(?<service>.*)/(?<method>.*)$", RegexOptions.Compiled);
public static string GetGrpcMethodFromActivity(Activity activity) public static string GetGrpcMethodFromActivity(Activity activity)
{ {

View File

@ -29,11 +29,11 @@ namespace OpenTelemetry.Instrumentation.GrpcNetClient.Implementation
internal static readonly AssemblyName AssemblyName = typeof(GrpcClientDiagnosticListener).Assembly.GetName(); internal static readonly AssemblyName AssemblyName = typeof(GrpcClientDiagnosticListener).Assembly.GetName();
internal static readonly string ActivitySourceName = AssemblyName.Name; internal static readonly string ActivitySourceName = AssemblyName.Name;
internal static readonly Version Version = AssemblyName.Version; internal static readonly Version Version = AssemblyName.Version;
internal static readonly ActivitySource ActivitySource = new ActivitySource(ActivitySourceName, Version.ToString()); internal static readonly ActivitySource ActivitySource = new(ActivitySourceName, Version.ToString());
private readonly GrpcClientInstrumentationOptions options; private readonly GrpcClientInstrumentationOptions options;
private readonly PropertyFetcher<HttpRequestMessage> startRequestFetcher = new PropertyFetcher<HttpRequestMessage>("Request"); private readonly PropertyFetcher<HttpRequestMessage> startRequestFetcher = new("Request");
private readonly PropertyFetcher<HttpResponseMessage> stopRequestFetcher = new PropertyFetcher<HttpResponseMessage>("Response"); private readonly PropertyFetcher<HttpResponseMessage> stopRequestFetcher = new("Response");
public GrpcClientDiagnosticListener(GrpcClientInstrumentationOptions options) public GrpcClientDiagnosticListener(GrpcClientInstrumentationOptions options)
: base("Grpc.Net.Client") : base("Grpc.Net.Client")

View File

@ -26,7 +26,7 @@ namespace OpenTelemetry.Instrumentation.GrpcNetClient.Implementation
[EventSource(Name = "OpenTelemetry-Instrumentation-Grpc")] [EventSource(Name = "OpenTelemetry-Instrumentation-Grpc")]
internal class GrpcInstrumentationEventSource : EventSource internal class GrpcInstrumentationEventSource : EventSource
{ {
public static GrpcInstrumentationEventSource Log = new GrpcInstrumentationEventSource(); public static GrpcInstrumentationEventSource Log = new();
[Event(1, Message = "Payload is NULL in event '{1}' from handler '{0}', span will not be recorded.", Level = EventLevel.Warning)] [Event(1, Message = "Payload is NULL in event '{1}' from handler '{0}', span will not be recorded.", Level = EventLevel.Warning)]
public void NullPayload(string handlerName, string eventName) public void NullPayload(string handlerName, string eventName)

View File

@ -33,14 +33,14 @@ namespace OpenTelemetry.Instrumentation.Http.Implementation
internal static readonly AssemblyName AssemblyName = typeof(HttpHandlerDiagnosticListener).Assembly.GetName(); internal static readonly AssemblyName AssemblyName = typeof(HttpHandlerDiagnosticListener).Assembly.GetName();
internal static readonly string ActivitySourceName = AssemblyName.Name; internal static readonly string ActivitySourceName = AssemblyName.Name;
internal static readonly Version Version = AssemblyName.Version; internal static readonly Version Version = AssemblyName.Version;
internal static readonly ActivitySource ActivitySource = new ActivitySource(ActivitySourceName, Version.ToString()); internal static readonly ActivitySource ActivitySource = new(ActivitySourceName, Version.ToString());
private static readonly Regex CoreAppMajorVersionCheckRegex = new Regex("^\\.NETCoreApp,Version=v(\\d+)\\.", RegexOptions.Compiled | RegexOptions.IgnoreCase); private static readonly Regex CoreAppMajorVersionCheckRegex = new("^\\.NETCoreApp,Version=v(\\d+)\\.", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private readonly PropertyFetcher<HttpRequestMessage> startRequestFetcher = new PropertyFetcher<HttpRequestMessage>("Request"); private readonly PropertyFetcher<HttpRequestMessage> startRequestFetcher = new("Request");
private readonly PropertyFetcher<HttpResponseMessage> stopResponseFetcher = new PropertyFetcher<HttpResponseMessage>("Response"); private readonly PropertyFetcher<HttpResponseMessage> stopResponseFetcher = new("Response");
private readonly PropertyFetcher<Exception> stopExceptionFetcher = new PropertyFetcher<Exception>("Exception"); private readonly PropertyFetcher<Exception> stopExceptionFetcher = new("Exception");
private readonly PropertyFetcher<TaskStatus> stopRequestStatusFetcher = new PropertyFetcher<TaskStatus>("RequestTaskStatus"); private readonly PropertyFetcher<TaskStatus> stopRequestStatusFetcher = new("RequestTaskStatus");
private readonly bool httpClientSupportsW3C; private readonly bool httpClientSupportsW3C;
private readonly HttpClientInstrumentationOptions options; private readonly HttpClientInstrumentationOptions options;

View File

@ -24,7 +24,7 @@ namespace OpenTelemetry.Instrumentation.Http.Implementation
{ {
internal class HttpHandlerMetricsDiagnosticListener : ListenerHandler internal class HttpHandlerMetricsDiagnosticListener : ListenerHandler
{ {
private readonly PropertyFetcher<HttpResponseMessage> stopResponseFetcher = new PropertyFetcher<HttpResponseMessage>("Response"); private readonly PropertyFetcher<HttpResponseMessage> stopResponseFetcher = new("Response");
private readonly Histogram<double> httpClientDuration; private readonly Histogram<double> httpClientDuration;
public HttpHandlerMetricsDiagnosticListener(string name, Meter meter) public HttpHandlerMetricsDiagnosticListener(string name, Meter meter)

View File

@ -26,7 +26,7 @@ namespace OpenTelemetry.Instrumentation.Http.Implementation
[EventSource(Name = "OpenTelemetry-Instrumentation-Http")] [EventSource(Name = "OpenTelemetry-Instrumentation-Http")]
internal class HttpInstrumentationEventSource : EventSource internal class HttpInstrumentationEventSource : EventSource
{ {
public static HttpInstrumentationEventSource Log = new HttpInstrumentationEventSource(); public static HttpInstrumentationEventSource Log = new();
[NonEvent] [NonEvent]
public void FailedProcessResult(Exception ex) public void FailedProcessResult(Exception ex)

View File

@ -24,11 +24,11 @@ namespace OpenTelemetry.Instrumentation.Http.Implementation
/// </summary> /// </summary>
internal static class HttpTagHelper internal static class HttpTagHelper
{ {
private static readonly ConcurrentDictionary<string, string> MethodOperationNameCache = new ConcurrentDictionary<string, string>(); private static readonly ConcurrentDictionary<string, string> MethodOperationNameCache = new();
private static readonly ConcurrentDictionary<HttpMethod, string> HttpMethodOperationNameCache = new ConcurrentDictionary<HttpMethod, string>(); private static readonly ConcurrentDictionary<HttpMethod, string> HttpMethodOperationNameCache = new();
private static readonly ConcurrentDictionary<HttpMethod, string> HttpMethodNameCache = new ConcurrentDictionary<HttpMethod, string>(); private static readonly ConcurrentDictionary<HttpMethod, string> HttpMethodNameCache = new();
private static readonly ConcurrentDictionary<string, ConcurrentDictionary<int, string>> HostAndPortToStringCache = new ConcurrentDictionary<string, ConcurrentDictionary<int, string>>(); private static readonly ConcurrentDictionary<string, ConcurrentDictionary<int, string>> HostAndPortToStringCache = new();
private static readonly ConcurrentDictionary<Version, string> ProtocolVersionToStringCache = new ConcurrentDictionary<Version, string>(); private static readonly ConcurrentDictionary<Version, string> ProtocolVersionToStringCache = new();
private static readonly Func<string, string> ConvertMethodToOperationNameRef = ConvertMethodToOperationName; private static readonly Func<string, string> ConvertMethodToOperationNameRef = ConvertMethodToOperationName;
private static readonly Func<HttpMethod, string> ConvertHttpMethodToOperationNameRef = ConvertHttpMethodToOperationName; private static readonly Func<HttpMethod, string> ConvertHttpMethodToOperationNameRef = ConvertHttpMethodToOperationName;

View File

@ -38,7 +38,7 @@ namespace OpenTelemetry.Instrumentation.SqlClient.Implementation
private static readonly Version Version = typeof(SqlActivitySourceHelper).Assembly.GetName().Version; private static readonly Version Version = typeof(SqlActivitySourceHelper).Assembly.GetName().Version;
#pragma warning disable SA1202 // Elements should be ordered by access <- In this case, Version MUST come before ActivitySource otherwise null ref exception is thrown. #pragma warning disable SA1202 // Elements should be ordered by access <- In this case, Version MUST come before ActivitySource otherwise null ref exception is thrown.
internal static readonly ActivitySource ActivitySource = new ActivitySource(ActivitySourceName, Version.ToString()); internal static readonly ActivitySource ActivitySource = new(ActivitySourceName, Version.ToString());
#pragma warning restore SA1202 // Elements should be ordered by access #pragma warning restore SA1202 // Elements should be ordered by access
} }
} }

View File

@ -32,13 +32,13 @@ namespace OpenTelemetry.Instrumentation.SqlClient.Implementation
public const string SqlDataWriteCommandError = "System.Data.SqlClient.WriteCommandError"; public const string SqlDataWriteCommandError = "System.Data.SqlClient.WriteCommandError";
public const string SqlMicrosoftWriteCommandError = "Microsoft.Data.SqlClient.WriteCommandError"; public const string SqlMicrosoftWriteCommandError = "Microsoft.Data.SqlClient.WriteCommandError";
private readonly PropertyFetcher<object> commandFetcher = new PropertyFetcher<object>("Command"); private readonly PropertyFetcher<object> commandFetcher = new("Command");
private readonly PropertyFetcher<object> connectionFetcher = new PropertyFetcher<object>("Connection"); private readonly PropertyFetcher<object> connectionFetcher = new("Connection");
private readonly PropertyFetcher<object> dataSourceFetcher = new PropertyFetcher<object>("DataSource"); private readonly PropertyFetcher<object> dataSourceFetcher = new("DataSource");
private readonly PropertyFetcher<object> databaseFetcher = new PropertyFetcher<object>("Database"); private readonly PropertyFetcher<object> databaseFetcher = new("Database");
private readonly PropertyFetcher<CommandType> commandTypeFetcher = new PropertyFetcher<CommandType>("CommandType"); private readonly PropertyFetcher<CommandType> commandTypeFetcher = new("CommandType");
private readonly PropertyFetcher<object> commandTextFetcher = new PropertyFetcher<object>("CommandText"); private readonly PropertyFetcher<object> commandTextFetcher = new("CommandText");
private readonly PropertyFetcher<Exception> exceptionFetcher = new PropertyFetcher<Exception>("Exception"); private readonly PropertyFetcher<Exception> exceptionFetcher = new("Exception");
private readonly SqlClientInstrumentationOptions options; private readonly SqlClientInstrumentationOptions options;
public SqlClientDiagnosticListener(string sourceName, SqlClientInstrumentationOptions options) public SqlClientDiagnosticListener(string sourceName, SqlClientInstrumentationOptions options)

View File

@ -26,7 +26,7 @@ namespace OpenTelemetry.Instrumentation.SqlClient.Implementation
[EventSource(Name = "OpenTelemetry-Instrumentation-SqlClient")] [EventSource(Name = "OpenTelemetry-Instrumentation-SqlClient")]
internal class SqlClientInstrumentationEventSource : EventSource internal class SqlClientInstrumentationEventSource : EventSource
{ {
public static SqlClientInstrumentationEventSource Log = new SqlClientInstrumentationEventSource(); public static SqlClientInstrumentationEventSource Log = new();
[NonEvent] [NonEvent]
public void UnknownErrorProcessingEvent(string handlerName, string eventName, Exception ex) public void UnknownErrorProcessingEvent(string handlerName, string eventName, Exception ex)

View File

@ -48,7 +48,7 @@ namespace OpenTelemetry.Instrumentation.SqlClient
* np:\\serverName\pipe\MSSQL$instanceName\pipeName - in this case a separate regex (see NamedPipeRegex below) * np:\\serverName\pipe\MSSQL$instanceName\pipeName - in this case a separate regex (see NamedPipeRegex below)
* is used to extract instanceName * is used to extract instanceName
*/ */
private static readonly Regex DataSourceRegex = new Regex("^(.*\\s*:\\s*\\\\{0,2})?(.*?)\\s*(?:[\\\\,]|$)\\s*(.*?)\\s*(?:,|$)\\s*(.*)$", RegexOptions.Compiled); private static readonly Regex DataSourceRegex = new("^(.*\\s*:\\s*\\\\{0,2})?(.*?)\\s*(?:[\\\\,]|$)\\s*(.*?)\\s*(?:,|$)\\s*(.*)$", RegexOptions.Compiled);
/// <summary> /// <summary>
/// In a Data Source string like "np:\\serverName\pipe\MSSQL$instanceName\pipeName" match the /// In a Data Source string like "np:\\serverName\pipe\MSSQL$instanceName\pipeName" match the
@ -57,9 +57,9 @@ namespace OpenTelemetry.Instrumentation.SqlClient
/// <see> /// <see>
/// <a href="https://docs.microsoft.com/previous-versions/sql/sql-server-2016/ms189307(v=sql.130)"/> /// <a href="https://docs.microsoft.com/previous-versions/sql/sql-server-2016/ms189307(v=sql.130)"/>
/// </see> /// </see>
private static readonly Regex NamedPipeRegex = new Regex("pipe\\\\MSSQL\\$(.*?)\\\\", RegexOptions.Compiled); private static readonly Regex NamedPipeRegex = new("pipe\\\\MSSQL\\$(.*?)\\\\", RegexOptions.Compiled);
private static readonly ConcurrentDictionary<string, SqlConnectionDetails> ConnectionDetailCache = new ConcurrentDictionary<string, SqlConnectionDetails>(StringComparer.OrdinalIgnoreCase); private static readonly ConcurrentDictionary<string, SqlConnectionDetails> ConnectionDetailCache = new(StringComparer.OrdinalIgnoreCase);
// .NET Framework implementation uses SqlEventSource from which we can't reliably distinguish // .NET Framework implementation uses SqlEventSource from which we can't reliably distinguish
// StoredProcedures from regular Text sql commands. // StoredProcedures from regular Text sql commands.

View File

@ -26,7 +26,7 @@ namespace OpenTelemetry.Instrumentation.StackExchangeRedis.Implementation
{ {
internal static class RedisProfilerEntryToActivityConverter internal static class RedisProfilerEntryToActivityConverter
{ {
private static readonly Lazy<Func<object, (string, string)>> MessageDataGetter = new Lazy<Func<object, (string, string)>>(() => private static readonly Lazy<Func<object, (string, string)>> MessageDataGetter = new(() =>
{ {
var redisAssembly = typeof(IProfiledCommand).Assembly; var redisAssembly = typeof(IProfiledCommand).Assembly;
Type profiledCommandType = redisAssembly.GetType("StackExchange.Redis.Profiling.ProfiledCommand"); Type profiledCommandType = redisAssembly.GetType("StackExchange.Redis.Profiling.ProfiledCommand");

View File

@ -37,20 +37,20 @@ namespace OpenTelemetry.Instrumentation.StackExchangeRedis
internal const string ActivitySourceName = "OpenTelemetry.StackExchange.Redis"; internal const string ActivitySourceName = "OpenTelemetry.StackExchange.Redis";
internal const string ActivityName = ActivitySourceName + ".Execute"; internal const string ActivityName = ActivitySourceName + ".Execute";
internal static readonly Version Version = typeof(StackExchangeRedisCallsInstrumentation).Assembly.GetName().Version; internal static readonly Version Version = typeof(StackExchangeRedisCallsInstrumentation).Assembly.GetName().Version;
internal static readonly ActivitySource ActivitySource = new ActivitySource(ActivitySourceName, Version.ToString()); internal static readonly ActivitySource ActivitySource = new(ActivitySourceName, Version.ToString());
internal static readonly IEnumerable<KeyValuePair<string, object>> CreationTags = new[] internal static readonly IEnumerable<KeyValuePair<string, object>> CreationTags = new[]
{ {
new KeyValuePair<string, object>(SemanticConventions.AttributeDbSystem, "redis"), new KeyValuePair<string, object>(SemanticConventions.AttributeDbSystem, "redis"),
}; };
internal readonly ConcurrentDictionary<(ActivityTraceId TraceId, ActivitySpanId SpanId), (Activity Activity, ProfilingSession Session)> Cache internal readonly ConcurrentDictionary<(ActivityTraceId TraceId, ActivitySpanId SpanId), (Activity Activity, ProfilingSession Session)> Cache
= new ConcurrentDictionary<(ActivityTraceId, ActivitySpanId), (Activity, ProfilingSession)>(); = new();
private readonly StackExchangeRedisCallsInstrumentationOptions options; private readonly StackExchangeRedisCallsInstrumentationOptions options;
private readonly EventWaitHandle stopHandle = new EventWaitHandle(false, EventResetMode.ManualReset); private readonly EventWaitHandle stopHandle = new(false, EventResetMode.ManualReset);
private readonly Thread drainThread; private readonly Thread drainThread;
private readonly ProfilingSession defaultSession = new ProfilingSession(); private readonly ProfilingSession defaultSession = new();
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="StackExchangeRedisCallsInstrumentation"/> class. /// Initializes a new instance of the <see cref="StackExchangeRedisCallsInstrumentation"/> class.

View File

@ -27,7 +27,7 @@ namespace OpenTelemetry.Shims.OpenTracing
{ {
internal sealed class ScopeManagerShim : IScopeManager internal sealed class ScopeManagerShim : IScopeManager
{ {
private static readonly ConditionalWeakTable<TelemetrySpan, IScope> SpanScopeTable = new ConditionalWeakTable<TelemetrySpan, IScope>(); private static readonly ConditionalWeakTable<TelemetrySpan, IScope> SpanScopeTable = new();
private readonly Tracer tracer; private readonly Tracer tracer;

View File

@ -43,12 +43,12 @@ namespace OpenTelemetry.Shims.OpenTracing
/// <summary> /// <summary>
/// The OpenTelemetry links. These correspond loosely to OpenTracing references. /// The OpenTelemetry links. These correspond loosely to OpenTracing references.
/// </summary> /// </summary>
private readonly List<Link> links = new List<Link>(); private readonly List<Link> links = new();
/// <summary> /// <summary>
/// The OpenTelemetry attributes. These correspond to OpenTracing Tags. /// The OpenTelemetry attributes. These correspond to OpenTracing Tags.
/// </summary> /// </summary>
private readonly List<KeyValuePair<string, object>> attributes = new List<KeyValuePair<string, object>>(); private readonly List<KeyValuePair<string, object>> attributes = new();
/// <summary> /// <summary>
/// The set of operation names for System.Diagnostics.Activity based automatic instrumentations that indicate a root span. /// The set of operation names for System.Diagnostics.Activity based automatic instrumentations that indicate a root span.

View File

@ -38,9 +38,9 @@ namespace OpenTelemetry
private readonly int exporterTimeoutMilliseconds; private readonly int exporterTimeoutMilliseconds;
private readonly int maxExportBatchSize; private readonly int maxExportBatchSize;
private readonly Thread exporterThread; private readonly Thread exporterThread;
private readonly AutoResetEvent exportTrigger = new AutoResetEvent(false); private readonly AutoResetEvent exportTrigger = new(false);
private readonly ManualResetEvent dataExportedNotification = new ManualResetEvent(false); private readonly ManualResetEvent dataExportedNotification = new(false);
private readonly ManualResetEvent shutdownTrigger = new ManualResetEvent(false); private readonly ManualResetEvent shutdownTrigger = new(false);
private long shutdownDrainTarget = long.MaxValue; private long shutdownDrainTarget = long.MaxValue;
private long droppedCount; private long droppedCount;
private bool disposed; private bool disposed;

View File

@ -26,7 +26,7 @@ namespace OpenTelemetry.Instrumentation
[EventSource(Name = "OpenTelemetry-Instrumentation")] [EventSource(Name = "OpenTelemetry-Instrumentation")]
internal class InstrumentationEventSource : EventSource internal class InstrumentationEventSource : EventSource
{ {
public static InstrumentationEventSource Log = new InstrumentationEventSource(); public static InstrumentationEventSource Log = new();
[Event(1, Message = "Current Activity is NULL in the '{0}' callback. Activity will not be recorded.", Level = EventLevel.Warning)] [Event(1, Message = "Current Activity is NULL in the '{0}' callback. Activity will not be recorded.", Level = EventLevel.Warning)]
public void NullActivity(string eventName) public void NullActivity(string eventName)

View File

@ -31,9 +31,9 @@ namespace OpenTelemetry.Internal
[EventSource(Name = "OpenTelemetry-Sdk")] [EventSource(Name = "OpenTelemetry-Sdk")]
internal class OpenTelemetrySdkEventSource : EventSource internal class OpenTelemetrySdkEventSource : EventSource
{ {
public static OpenTelemetrySdkEventSource Log = new OpenTelemetrySdkEventSource(); public static OpenTelemetrySdkEventSource Log = new();
#if DEBUG #if DEBUG
public static OpenTelemetryEventListener Listener = new OpenTelemetryEventListener(); public static OpenTelemetryEventListener Listener = new();
#endif #endif
[NonEvent] [NonEvent]
@ -381,7 +381,7 @@ namespace OpenTelemetry.Internal
#if DEBUG #if DEBUG
public class OpenTelemetryEventListener : EventListener public class OpenTelemetryEventListener : EventListener
{ {
private readonly List<EventSource> eventSources = new List<EventSource>(); private readonly List<EventSource> eventSources = new();
public override void Dispose() public override void Dispose()
{ {

View File

@ -23,7 +23,7 @@ namespace OpenTelemetry.Exporter
{ {
internal static class PeerServiceResolver internal static class PeerServiceResolver
{ {
private static readonly Dictionary<string, int> PeerServiceKeyResolutionDictionary = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase) private static readonly Dictionary<string, int> PeerServiceKeyResolutionDictionary = new(StringComparer.OrdinalIgnoreCase)
{ {
[SemanticConventions.AttributePeerService] = 0, // priority 0 (highest). [SemanticConventions.AttributePeerService] = 0, // priority 0 (highest).
["peer.hostname"] = 1, ["peer.hostname"] = 1,

View File

@ -27,7 +27,7 @@ namespace OpenTelemetry.Internal
/// <summary> /// <summary>
/// Long-living object that hold relevant resources. /// Long-living object that hold relevant resources.
/// </summary> /// </summary>
private static readonly SelfDiagnostics Instance = new SelfDiagnostics(); private static readonly SelfDiagnostics Instance = new();
private readonly SelfDiagnosticsConfigRefresher configRefresher; private readonly SelfDiagnosticsConfigRefresher configRefresher;
static SelfDiagnostics() static SelfDiagnostics()

View File

@ -33,13 +33,13 @@ namespace OpenTelemetry.Internal
/// </summary> /// </summary>
private const int ConfigBufferSize = 4 * 1024; private const int ConfigBufferSize = 4 * 1024;
private static readonly Regex LogDirectoryRegex = new Regex( private static readonly Regex LogDirectoryRegex = new(
@"""LogDirectory""\s*:\s*""(?<LogDirectory>.*?)""", RegexOptions.IgnoreCase | RegexOptions.Compiled); @"""LogDirectory""\s*:\s*""(?<LogDirectory>.*?)""", RegexOptions.IgnoreCase | RegexOptions.Compiled);
private static readonly Regex FileSizeRegex = new Regex( private static readonly Regex FileSizeRegex = new(
@"""FileSize""\s*:\s*(?<FileSize>\d+)", RegexOptions.IgnoreCase | RegexOptions.Compiled); @"""FileSize""\s*:\s*(?<FileSize>\d+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
private static readonly Regex LogLevelRegex = new Regex( private static readonly Regex LogLevelRegex = new(
@"""LogLevel""\s*:\s*""(?<LogLevel>.*?)""", RegexOptions.IgnoreCase | RegexOptions.Compiled); @"""LogLevel""\s*:\s*""(?<LogLevel>.*?)""", RegexOptions.IgnoreCase | RegexOptions.Compiled);
// This class is called in SelfDiagnosticsConfigRefresher.UpdateMemoryMappedFileFromConfiguration // This class is called in SelfDiagnosticsConfigRefresher.UpdateMemoryMappedFileFromConfiguration

View File

@ -46,8 +46,8 @@ namespace OpenTelemetry.Internal
/// memoryMappedFileCache is a handle kept in thread-local storage as a cache to indicate whether the cached /// memoryMappedFileCache is a handle kept in thread-local storage as a cache to indicate whether the cached
/// viewStream is created from the current m_memoryMappedFile. /// viewStream is created from the current m_memoryMappedFile.
/// </summary> /// </summary>
private readonly ThreadLocal<MemoryMappedFile> memoryMappedFileCache = new ThreadLocal<MemoryMappedFile>(true); private readonly ThreadLocal<MemoryMappedFile> memoryMappedFileCache = new(true);
private readonly ThreadLocal<MemoryMappedViewStream> viewStream = new ThreadLocal<MemoryMappedViewStream>(true); private readonly ThreadLocal<MemoryMappedViewStream> viewStream = new(true);
private bool disposedValue; private bool disposedValue;
// Once the configuration file is valid, an eventListener object will be created. // Once the configuration file is valid, an eventListener object will be created.

View File

@ -33,11 +33,11 @@ namespace OpenTelemetry.Internal
// Buffer size of the log line. A UTF-16 encoded character in C# can take up to 4 bytes if encoded in UTF-8. // Buffer size of the log line. A UTF-16 encoded character in C# can take up to 4 bytes if encoded in UTF-8.
private const int BUFFERSIZE = 4 * 5120; private const int BUFFERSIZE = 4 * 5120;
private const string EventSourceNamePrefix = "OpenTelemetry-"; private const string EventSourceNamePrefix = "OpenTelemetry-";
private readonly object lockObj = new object(); private readonly object lockObj = new();
private readonly EventLevel logLevel; private readonly EventLevel logLevel;
private readonly SelfDiagnosticsConfigRefresher configRefresher; private readonly SelfDiagnosticsConfigRefresher configRefresher;
private readonly ThreadLocal<byte[]> writeBuffer = new ThreadLocal<byte[]>(() => null); private readonly ThreadLocal<byte[]> writeBuffer = new(() => null);
private readonly List<EventSource> eventSourcesBeforeConstructor = new List<EventSource>(); private readonly List<EventSource> eventSourcesBeforeConstructor = new();
private bool disposedValue = false; private bool disposedValue = false;

View File

@ -40,7 +40,7 @@ namespace OpenTelemetry.Logs
/// of the scope. /// of the scope.
/// </summary> /// </summary>
/// <returns><see cref="Enumerator"/>.</returns> /// <returns><see cref="Enumerator"/>.</returns>
public Enumerator GetEnumerator() => new Enumerator(this.Scope); public Enumerator GetEnumerator() => new(this.Scope);
/// <summary> /// <summary>
/// LogRecordScope enumerator. /// LogRecordScope enumerator.

View File

@ -22,7 +22,7 @@ namespace OpenTelemetry.Logs
{ {
public class OpenTelemetryLoggerOptions public class OpenTelemetryLoggerOptions
{ {
internal readonly List<BaseProcessor<LogRecord>> Processors = new List<BaseProcessor<LogRecord>>(); internal readonly List<BaseProcessor<LogRecord>> Processors = new();
internal ResourceBuilder ResourceBuilder = ResourceBuilder.CreateDefault(); internal ResourceBuilder ResourceBuilder = ResourceBuilder.CreateDefault();
/// <summary> /// <summary>

View File

@ -28,7 +28,7 @@ namespace OpenTelemetry.Logs
internal readonly OpenTelemetryLoggerOptions Options; internal readonly OpenTelemetryLoggerOptions Options;
internal BaseProcessor<LogRecord> Processor; internal BaseProcessor<LogRecord> Processor;
internal Resource Resource; internal Resource Resource;
private readonly Hashtable loggers = new Hashtable(); private readonly Hashtable loggers = new();
private bool disposed; private bool disposed;
private IExternalScopeProvider scopeProvider; private IExternalScopeProvider scopeProvider;

View File

@ -26,12 +26,12 @@ namespace OpenTelemetry.Metrics
internal sealed class AggregatorStore internal sealed class AggregatorStore
{ {
private static readonly string MetricPointCapHitFixMessage = "Modify instrumentation to reduce the number of unique key/value pair combinations. Or use Views to drop unwanted tags. Or use MeterProviderBuilder.SetMaxMetricPointsPerMetricStream to set higher limit."; private static readonly string MetricPointCapHitFixMessage = "Modify instrumentation to reduce the number of unique key/value pair combinations. Or use Views to drop unwanted tags. Or use MeterProviderBuilder.SetMaxMetricPointsPerMetricStream to set higher limit.";
private readonly object lockZeroTags = new object(); private readonly object lockZeroTags = new();
private readonly HashSet<string> tagKeysInteresting; private readonly HashSet<string> tagKeysInteresting;
private readonly int tagsKeysInterestingCount; private readonly int tagsKeysInterestingCount;
private readonly ConcurrentDictionary<Tags, int> tagsToMetricPointIndexDictionary = private readonly ConcurrentDictionary<Tags, int> tagsToMetricPointIndexDictionary =
new ConcurrentDictionary<Tags, int>(); new();
private readonly string name; private readonly string name;
private readonly string metricPointCapHitMessage; private readonly string metricPointCapHitMessage;

View File

@ -67,7 +67,7 @@ namespace OpenTelemetry.Metrics
return this; return this;
} }
public Enumerator GetEnumerator() => new Enumerator(this.head); public Enumerator GetEnumerator() => new(this.head);
/// <inheritdoc/> /// <inheritdoc/>
internal override bool ProcessMetrics(in Batch<Metric> metrics, int timeoutMilliseconds) internal override bool ProcessMetrics(in Batch<Metric> metrics, int timeoutMilliseconds)

View File

@ -31,9 +31,9 @@ namespace OpenTelemetry.Metrics
{ {
internal const int MaxMetricsDefault = 1000; internal const int MaxMetricsDefault = 1000;
internal const int MaxMetricPointsPerMetricDefault = 2000; internal const int MaxMetricPointsPerMetricDefault = 2000;
private readonly List<InstrumentationFactory> instrumentationFactories = new List<InstrumentationFactory>(); private readonly List<InstrumentationFactory> instrumentationFactories = new();
private readonly List<string> meterSources = new List<string>(); private readonly List<string> meterSources = new();
private readonly List<Func<Instrument, MetricStreamConfiguration>> viewConfigs = new List<Func<Instrument, MetricStreamConfiguration>>(); private readonly List<Func<Instrument, MetricStreamConfiguration>> viewConfigs = new();
private ResourceBuilder resourceBuilder = ResourceBuilder.CreateDefault(); private ResourceBuilder resourceBuilder = ResourceBuilder.CreateDefault();
private int maxMetricStreams = MaxMetricsDefault; private int maxMetricStreams = MaxMetricsDefault;
private int maxMetricPointsPerMetricStream = MaxMetricPointsPerMetricDefault; private int maxMetricPointsPerMetricStream = MaxMetricPointsPerMetricDefault;

View File

@ -20,7 +20,7 @@ namespace OpenTelemetry.Metrics
{ {
internal class MeterProviderBuilderSdk : MeterProviderBuilderBase internal class MeterProviderBuilderSdk : MeterProviderBuilderBase
{ {
private static readonly Regex InstrumentNameRegex = new Regex( private static readonly Regex InstrumentNameRegex = new(
@"^[a-zA-Z][-.\w]{0,62}$", RegexOptions.IgnoreCase | RegexOptions.Compiled); @"^[a-zA-Z][-.\w]{0,62}$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
/// <summary> /// <summary>

View File

@ -28,9 +28,9 @@ namespace OpenTelemetry.Metrics
internal sealed class MeterProviderSdk : MeterProvider internal sealed class MeterProviderSdk : MeterProvider
{ {
internal int ShutdownCount; internal int ShutdownCount;
private readonly List<object> instrumentations = new List<object>(); private readonly List<object> instrumentations = new();
private readonly List<Func<Instrument, MetricStreamConfiguration>> viewConfigs; private readonly List<Func<Instrument, MetricStreamConfiguration>> viewConfigs;
private readonly object collectLock = new object(); private readonly object collectLock = new();
private readonly MeterListener listener; private readonly MeterListener listener;
private readonly MetricReader reader; private readonly MetricReader reader;
private readonly CompositeMetricReader compositeMetricReader; private readonly CompositeMetricReader compositeMetricReader;

View File

@ -28,9 +28,9 @@ namespace OpenTelemetry.Metrics
public abstract partial class MetricReader : IDisposable public abstract partial class MetricReader : IDisposable
{ {
private const AggregationTemporality AggregationTemporalityUnspecified = (AggregationTemporality)0; private const AggregationTemporality AggregationTemporalityUnspecified = (AggregationTemporality)0;
private readonly object newTaskLock = new object(); private readonly object newTaskLock = new();
private readonly object onCollectLock = new object(); private readonly object onCollectLock = new();
private readonly TaskCompletionSource<bool> shutdownTcs = new TaskCompletionSource<bool>(); private readonly TaskCompletionSource<bool> shutdownTcs = new();
private AggregationTemporality temporality = AggregationTemporalityUnspecified; private AggregationTemporality temporality = AggregationTemporalityUnspecified;
private int shutdownCount; private int shutdownCount;
private TaskCompletionSource<bool> collectionTcs; private TaskCompletionSource<bool> collectionTcs;

View File

@ -27,9 +27,9 @@ namespace OpenTelemetry.Metrics
/// </summary> /// </summary>
public abstract partial class MetricReader public abstract partial class MetricReader
{ {
private readonly HashSet<string> metricStreamNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); private readonly HashSet<string> metricStreamNames = new(StringComparer.OrdinalIgnoreCase);
private readonly ConcurrentDictionary<InstrumentIdentity, Metric> instrumentIdentityToMetric = new ConcurrentDictionary<InstrumentIdentity, Metric>(); private readonly ConcurrentDictionary<InstrumentIdentity, Metric> instrumentIdentityToMetric = new();
private readonly object instrumentCreationLock = new object(); private readonly object instrumentCreationLock = new();
private int maxMetricStreams; private int maxMetricStreams;
private int maxMetricPointsPerMetricStream; private int maxMetricPointsPerMetricStream;
private Metric[] metrics; private Metric[] metrics;

View File

@ -34,8 +34,8 @@ namespace OpenTelemetry.Metrics
private readonly int exportIntervalMilliseconds; private readonly int exportIntervalMilliseconds;
private readonly int exportTimeoutMilliseconds; private readonly int exportTimeoutMilliseconds;
private readonly Thread exporterThread; private readonly Thread exporterThread;
private readonly AutoResetEvent exportTrigger = new AutoResetEvent(false); private readonly AutoResetEvent exportTrigger = new(false);
private readonly ManualResetEvent shutdownTrigger = new ManualResetEvent(false); private readonly ManualResetEvent shutdownTrigger = new(false);
private bool disposed; private bool disposed;
/// <summary> /// <summary>

View File

@ -24,7 +24,7 @@ namespace OpenTelemetry.Resources
/// </summary> /// </summary>
public class ResourceBuilder public class ResourceBuilder
{ {
private readonly List<Resource> resources = new List<Resource>(); private readonly List<Resource> resources = new();
private ResourceBuilder() private ResourceBuilder()
{ {
@ -57,7 +57,7 @@ namespace OpenTelemetry.Resources
/// </summary> /// </summary>
/// <returns>Created <see cref="ResourceBuilder"/>.</returns> /// <returns>Created <see cref="ResourceBuilder"/>.</returns>
public static ResourceBuilder CreateEmpty() public static ResourceBuilder CreateEmpty()
=> new ResourceBuilder(); => new();
/// <summary> /// <summary>
/// Clears the <see cref="Resource"/>s added to the builder. /// Clears the <see cref="Resource"/>s added to the builder.

View File

@ -26,7 +26,7 @@ namespace OpenTelemetry
public abstract class SimpleExportProcessor<T> : BaseExportProcessor<T> public abstract class SimpleExportProcessor<T> : BaseExportProcessor<T>
where T : class where T : class
{ {
private readonly object syncObject = new object(); private readonly object syncObject = new();
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="SimpleExportProcessor{T}"/> class. /// Initializes a new instance of the <see cref="SimpleExportProcessor{T}"/> class.

View File

@ -27,10 +27,10 @@ namespace OpenTelemetry.Trace
/// </summary> /// </summary>
public abstract class TracerProviderBuilderBase : TracerProviderBuilder public abstract class TracerProviderBuilderBase : TracerProviderBuilder
{ {
private readonly List<InstrumentationFactory> instrumentationFactories = new List<InstrumentationFactory>(); private readonly List<InstrumentationFactory> instrumentationFactories = new();
private readonly List<BaseProcessor<Activity>> processors = new List<BaseProcessor<Activity>>(); private readonly List<BaseProcessor<Activity>> processors = new();
private readonly List<string> sources = new List<string>(); private readonly List<string> sources = new();
private readonly HashSet<string> legacyActivityOperationNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); private readonly HashSet<string> legacyActivityOperationNames = new(StringComparer.OrdinalIgnoreCase);
private ResourceBuilder resourceBuilder = ResourceBuilder.CreateDefault(); private ResourceBuilder resourceBuilder = ResourceBuilder.CreateDefault();
private Sampler sampler = new ParentBasedSampler(new AlwaysOnSampler()); private Sampler sampler = new ParentBasedSampler(new AlwaysOnSampler());

View File

@ -28,7 +28,7 @@ namespace OpenTelemetry.Trace
{ {
internal int ShutdownCount; internal int ShutdownCount;
private readonly List<object> instrumentations = new List<object>(); private readonly List<object> instrumentations = new();
private readonly ActivityListener listener; private readonly ActivityListener listener;
private readonly Sampler sampler; private readonly Sampler sampler;
private readonly Action<Activity> getRequestedDataAction; private readonly Action<Activity> getRequestedDataAction;

View File

@ -31,7 +31,7 @@ namespace Benchmarks.Exporter
{ {
private Meter meter; private Meter meter;
private MeterProvider meterProvider; private MeterProvider meterProvider;
private List<Metric> metrics = new List<Metric>(); private List<Metric> metrics = new();
private byte[] buffer = new byte[85000]; private byte[] buffer = new byte[85000];
[Params(1, 1000, 10000)] [Params(1, 1000, 10000)]

View File

@ -34,8 +34,8 @@ namespace Benchmarks.Instrumentation
private const string SourceName = "MySource"; private const string SourceName = "MySource";
private readonly DiagnosticListener listener = new DiagnosticListener(SourceName); private readonly DiagnosticListener listener = new(SourceName);
private readonly List<DiagnosticSourceSubscriber> subscribers = new List<DiagnosticSourceSubscriber>(); private readonly List<DiagnosticSourceSubscriber> subscribers = new();
private readonly Func<string, object, object, bool> isEnabledFilter = (name, arg1, arg2) => ((EventPayload)arg1).Data == "Data"; private readonly Func<string, object, object, bool> isEnabledFilter = (name, arg1, arg2) => ((EventPayload)arg1).Data == "Data";
[GlobalSetup] [GlobalSetup]

View File

@ -26,7 +26,7 @@ namespace Benchmarks.Logs
[MemoryDiagnoser] [MemoryDiagnoser]
public class LogScopeBenchmarks public class LogScopeBenchmarks
{ {
private readonly LoggerExternalScopeProvider scopeProvider = new LoggerExternalScopeProvider(); private readonly LoggerExternalScopeProvider scopeProvider = new();
private readonly Action<LogRecordScope, object> callback = (LogRecordScope scope, object state) => private readonly Action<LogRecordScope, object> callback = (LogRecordScope scope, object state) =>
{ {

View File

@ -61,7 +61,7 @@ namespace Benchmarks.Metrics
public class HistogramBenchmarks public class HistogramBenchmarks
{ {
private const int MaxValue = 1000; private const int MaxValue = 1000;
private Random random = new Random(); private Random random = new();
private Histogram<long> histogram; private Histogram<long> histogram;
private MeterProvider provider; private MeterProvider provider;
private Meter meter; private Meter meter;

View File

@ -52,7 +52,7 @@ namespace Benchmarks.Metrics
private string[] dimensionValues = new string[] { "DimVal1", "DimVal2", "DimVal3", "DimVal4", "DimVal5", "DimVal6", "DimVal7", "DimVal8", "DimVal9", "DimVal10" }; private string[] dimensionValues = new string[] { "DimVal1", "DimVal2", "DimVal3", "DimVal4", "DimVal5", "DimVal6", "DimVal7", "DimVal8", "DimVal9", "DimVal10" };
// TODO: Confirm if this needs to be thread-safe // TODO: Confirm if this needs to be thread-safe
private Random random = new Random(); private Random random = new();
[Params(false, true)] [Params(false, true)]
public bool UseWithRef { get; set; } public bool UseWithRef { get; set; }

View File

@ -58,7 +58,7 @@ namespace Benchmarks.Metrics
private Counter<long> counter; private Counter<long> counter;
private MeterProvider provider; private MeterProvider provider;
private Meter meter; private Meter meter;
private Random random = new Random(); private Random random = new();
private string[] dimensionValues = new string[] { "DimVal1", "DimVal2", "DimVal3", "DimVal4", "DimVal5", "DimVal6", "DimVal7", "DimVal8", "DimVal9", "DimVal10" }; private string[] dimensionValues = new string[] { "DimVal1", "DimVal2", "DimVal3", "DimVal4", "DimVal5", "DimVal6", "DimVal7", "DimVal8", "DimVal9", "DimVal10" };
[Params(AggregationTemporality.Cumulative, AggregationTemporality.Delta)] [Params(AggregationTemporality.Cumulative, AggregationTemporality.Delta)]

View File

@ -43,7 +43,7 @@ namespace Benchmarks.Metrics
[MemoryDiagnoser] [MemoryDiagnoser]
public class MetricsViewBenchmarks public class MetricsViewBenchmarks
{ {
private static readonly ThreadLocal<Random> ThreadLocalRandom = new ThreadLocal<Random>(() => new Random()); private static readonly ThreadLocal<Random> ThreadLocalRandom = new(() => new Random());
private static readonly string[] DimensionValues = new string[] { "DimVal1", "DimVal2", "DimVal3", "DimVal4", "DimVal5", "DimVal6", "DimVal7", "DimVal8", "DimVal9", "DimVal10" }; private static readonly string[] DimensionValues = new string[] { "DimVal1", "DimVal2", "DimVal3", "DimVal4", "DimVal5", "DimVal6", "DimVal7", "DimVal8", "DimVal9", "DimVal10" };
private static readonly int DimensionsValuesLength = DimensionValues.Length; private static readonly int DimensionsValuesLength = DimensionValues.Length;
private List<Metric> metrics; private List<Metric> metrics;

View File

@ -25,8 +25,8 @@ namespace Benchmarks.Trace
[MemoryDiagnoser] [MemoryDiagnoser]
public class OpenTelemetrySdkBenchmarksActivity public class OpenTelemetrySdkBenchmarksActivity
{ {
private readonly ActivitySource benchmarkSource = new ActivitySource("Benchmark"); private readonly ActivitySource benchmarkSource = new("Benchmark");
private readonly ActivityContext parentCtx = new ActivityContext(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.None); private readonly ActivityContext parentCtx = new(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom(), ActivityTraceFlags.None);
private readonly string parentId = $"00-{ActivityTraceId.CreateRandom()}.{ActivitySpanId.CreateRandom()}.00"; private readonly string parentId = $"00-{ActivityTraceId.CreateRandom()}.{ActivitySpanId.CreateRandom()}.00";
private TracerProvider tracerProvider; private TracerProvider tracerProvider;

View File

@ -24,15 +24,15 @@ namespace Benchmarks.Trace
[MemoryDiagnoser] [MemoryDiagnoser]
public class TraceBenchmarks public class TraceBenchmarks
{ {
private readonly ActivitySource sourceWithNoListener = new ActivitySource("Benchmark.NoListener"); private readonly ActivitySource sourceWithNoListener = new("Benchmark.NoListener");
private readonly ActivitySource sourceWithPropagationDataListner = new ActivitySource("Benchmark.PropagationDataListner"); private readonly ActivitySource sourceWithPropagationDataListner = new("Benchmark.PropagationDataListner");
private readonly ActivitySource sourceWithAllDataListner = new ActivitySource("Benchmark.AllDataListner"); private readonly ActivitySource sourceWithAllDataListner = new("Benchmark.AllDataListner");
private readonly ActivitySource sourceWithAllDataAndRecordedListner = new ActivitySource("Benchmark.AllDataAndRecordedListner"); private readonly ActivitySource sourceWithAllDataAndRecordedListner = new("Benchmark.AllDataAndRecordedListner");
private readonly ActivitySource sourceWithOneProcessor = new ActivitySource("Benchmark.OneProcessor"); private readonly ActivitySource sourceWithOneProcessor = new("Benchmark.OneProcessor");
private readonly ActivitySource sourceWithTwoProcessors = new ActivitySource("Benchmark.TwoProcessors"); private readonly ActivitySource sourceWithTwoProcessors = new("Benchmark.TwoProcessors");
private readonly ActivitySource sourceWithThreeProcessors = new ActivitySource("Benchmark.ThreeProcessors"); private readonly ActivitySource sourceWithThreeProcessors = new("Benchmark.ThreeProcessors");
private readonly ActivitySource sourceWithOneLegacyActivityOperationNameSubscription = new ActivitySource("Benchmark.OneInstrumentation"); private readonly ActivitySource sourceWithOneLegacyActivityOperationNameSubscription = new("Benchmark.OneInstrumentation");
private readonly ActivitySource sourceWithTwoLegacyActivityOperationNameSubscriptions = new ActivitySource("Benchmark.TwoInstrumentations"); private readonly ActivitySource sourceWithTwoLegacyActivityOperationNameSubscriptions = new("Benchmark.TwoInstrumentations");
public TraceBenchmarks() public TraceBenchmarks()
{ {

View File

@ -30,7 +30,7 @@ namespace OpenTelemetry.Exporter.ZPages.Tests
{ {
public class ZPagesExporterTests public class ZPagesExporterTests
{ {
private static readonly HttpClient HttpClient = new HttpClient(); private static readonly HttpClient HttpClient = new();
static ZPagesExporterTests() static ZPagesExporterTests()
{ {

View File

@ -25,7 +25,7 @@ namespace OpenTelemetry.Exporter.Zipkin.Implementation.Tests
public class ZipkinActivityConversionTest public class ZipkinActivityConversionTest
{ {
private const string ZipkinSpanName = "Name"; private const string ZipkinSpanName = "Name";
private static readonly ZipkinEndpoint DefaultZipkinEndpoint = new ZipkinEndpoint("TestService"); private static readonly ZipkinEndpoint DefaultZipkinEndpoint = new("TestService");
[Fact] [Fact]
public void ToZipkinSpan_AllPropertiesSet() public void ToZipkinSpan_AllPropertiesSet()

View File

@ -23,7 +23,7 @@ namespace OpenTelemetry.Exporter.Zipkin.Implementation.Tests
{ {
public class ZipkinActivityExporterRemoteEndpointTests public class ZipkinActivityExporterRemoteEndpointTests
{ {
private static readonly ZipkinEndpoint DefaultZipkinEndpoint = new ZipkinEndpoint("TestService"); private static readonly ZipkinEndpoint DefaultZipkinEndpoint = new("TestService");
[Fact] [Fact]
public void GenerateActivity_RemoteEndpointOmittedByDefault() public void GenerateActivity_RemoteEndpointOmittedByDefault()

View File

@ -35,7 +35,7 @@ namespace OpenTelemetry.Exporter.Zipkin.Tests
public class ZipkinExporterTests : IDisposable public class ZipkinExporterTests : IDisposable
{ {
private const string TraceId = "e8ea7e9ac72de94e91fabc613f9686b2"; private const string TraceId = "e8ea7e9ac72de94e91fabc613f9686b2";
private static readonly ConcurrentDictionary<Guid, string> Responses = new ConcurrentDictionary<Guid, string>(); private static readonly ConcurrentDictionary<Guid, string> Responses = new();
private readonly IDisposable testServer; private readonly IDisposable testServer;
private readonly string testServerHost; private readonly string testServerHost;

View File

@ -470,7 +470,7 @@ namespace OpenTelemetry.Instrumentation.AspNet.Tests
private class TestHttpRequest : HttpRequestBase private class TestHttpRequest : HttpRequestBase
{ {
private readonly NameValueCollection headers = new NameValueCollection(); private readonly NameValueCollection headers = new();
public override NameValueCollection Headers => this.headers; public override NameValueCollection Headers => this.headers;

View File

@ -26,7 +26,7 @@ namespace OpenTelemetry.Instrumentation.Grpc.Tests
public class GrpcServer<TService> : IDisposable public class GrpcServer<TService> : IDisposable
where TService : class where TService : class
{ {
private static readonly Random GlobalRandom = new Random(); private static readonly Random GlobalRandom = new();
private readonly IHost host; private readonly IHost host;

View File

@ -183,7 +183,7 @@ namespace OpenTelemetry.Shims.OpenTracing.Tests
/// <seealso cref="OpenTracing.Propagation.ITextMap" /> /// <seealso cref="OpenTracing.Propagation.ITextMap" />
private class TextMapCarrier : ITextMap private class TextMapCarrier : ITextMap
{ {
private readonly Dictionary<string, string> map = new Dictionary<string, string>(); private readonly Dictionary<string, string> map = new();
public IDictionary<string, string> Map => this.map; public IDictionary<string, string> Map => this.map;
@ -203,7 +203,7 @@ namespace OpenTelemetry.Shims.OpenTracing.Tests
/// <seealso cref="OpenTracing.Propagation.IBinary" /> /// <seealso cref="OpenTracing.Propagation.IBinary" />
private class BinaryCarrier : IBinary private class BinaryCarrier : IBinary
{ {
private readonly MemoryStream carrierStream = new MemoryStream(); private readonly MemoryStream carrierStream = new();
public MemoryStream Get() => this.carrierStream; public MemoryStream Get() => this.carrierStream;

View File

@ -29,10 +29,10 @@ public partial class Program
// Note: Uncomment the below line if you want to run Histogram stress test // Note: Uncomment the below line if you want to run Histogram stress test
// private const int MaxHistogramMeasurement = 1000; // private const int MaxHistogramMeasurement = 1000;
private static readonly Meter TestMeter = new Meter(Utils.GetCurrentMethodName()); private static readonly Meter TestMeter = new(Utils.GetCurrentMethodName());
private static readonly Counter<long> TestCounter = TestMeter.CreateCounter<long>("TestCounter"); private static readonly Counter<long> TestCounter = TestMeter.CreateCounter<long>("TestCounter");
private static readonly string[] DimensionValues = new string[ArraySize]; private static readonly string[] DimensionValues = new string[ArraySize];
private static readonly ThreadLocal<Random> ThreadLocalRandom = new ThreadLocal<Random>(() => new Random()); private static readonly ThreadLocal<Random> ThreadLocalRandom = new(() => new Random());
// Note: Uncomment the below line if you want to run Histogram stress test // Note: Uncomment the below line if you want to run Histogram stress test
// private static readonly Histogram<long> TestHistogram = TestMeter.CreateHistogram<long>("TestHistogram"); // private static readonly Histogram<long> TestHistogram = TestMeter.CreateHistogram<long>("TestHistogram");

View File

@ -27,7 +27,7 @@ namespace OpenTelemetry.Tests.Stress;
public partial class Program public partial class Program
{ {
private static readonly Meter StressMeter = new Meter("OpenTelemetry.Tests.Stress"); private static readonly Meter StressMeter = new("OpenTelemetry.Tests.Stress");
private static volatile bool bContinue = true; private static volatile bool bContinue = true;
private static volatile string output = "Test results not available yet."; private static volatile string output = "Test results not available yet.";

Some files were not shown because too many files have changed in this diff Show More