Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use some collection expressions #6106

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
6 changes: 3 additions & 3 deletions docs/metrics/customizing-the-sdk/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,19 @@ public static void Main()
.AddView(instrumentName: "MyCounter", name: "MyCounterRenamed")

// Change Histogram boundaries using the Explicit Bucket Histogram aggregation.
.AddView(instrumentName: "MyHistogram", new ExplicitBucketHistogramConfiguration() { Boundaries = new double[] { 10, 20 } })
.AddView(instrumentName: "MyHistogram", new ExplicitBucketHistogramConfiguration() { Boundaries = [10.0, 20.0] })

// Change Histogram to use the Base2 Exponential Bucket Histogram aggregation.
.AddView(instrumentName: "MyExponentialBucketHistogram", new Base2ExponentialBucketHistogramConfiguration())

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

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

// Configure the Explicit Bucket Histogram aggregation with custom boundaries and new name.
.AddView(instrumentName: "histogramWithMultipleAggregations", new ExplicitBucketHistogramConfiguration() { Boundaries = new double[] { 10, 20 }, Name = "MyHistogramWithExplicitHistogram" })
.AddView(instrumentName: "histogramWithMultipleAggregations", new ExplicitBucketHistogramConfiguration() { Boundaries = [10.0, 20.0], Name = "MyHistogramWithExplicitHistogram" })

// Use Base2 Exponential Bucket Histogram aggregation and new name.
.AddView(instrumentName: "histogramWithMultipleAggregations", new Base2ExponentialBucketHistogramConfiguration() { Name = "MyHistogramWithBase2ExponentialBucketHistogram" })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ namespace Examples.AspNetCore.Controllers;
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching",
};
private static readonly string[] Summaries =
[
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
];

private static readonly HttpClient HttpClient = new();

Expand Down
2 changes: 1 addition & 1 deletion examples/Console/TestPrometheusExporter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ internal static int Run(PrometheusOptions options)
.AddMeter(MyMeter.Name)
.AddMeter(MyMeter2.Name)
.AddPrometheusHttpListener(
o => o.UriPrefixes = new string[] { $"http://localhost:{options.Port}/" })
o => o.UriPrefixes = [$"http://localhost:{options.Port}/"])
.Build();

var process = Process.GetCurrentProcess();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public sealed class B3Propagator : TextMapPropagator
// "Debug" sampled value.
internal const string FlagsValue = "1";

private static readonly HashSet<string> AllFields = new() { XB3TraceId, XB3SpanId, XB3ParentSpanId, XB3Sampled, XB3Flags };
private static readonly HashSet<string> AllFields = [XB3TraceId, XB3SpanId, XB3ParentSpanId, XB3Sampled, XB3Flags];

private static readonly HashSet<string> SampledValues = new(StringComparer.Ordinal) { SampledValue, LegacySampledValue };

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ public class BaggagePropagator : TextMapPropagator
private const int MaxBaggageLength = 8192;
private const int MaxBaggageItems = 180;

private static readonly char[] EqualSignSeparator = new[] { '=' };
private static readonly char[] CommaSignSeparator = new[] { ',' };
private static readonly char[] EqualSignSeparator = ['='];
private static readonly char[] CommaSignSeparator = [','];

/// <inheritdoc/>
public override ISet<string> Fields => new HashSet<string> { BaggageHeaderName };
Expand Down
8 changes: 4 additions & 4 deletions src/OpenTelemetry.Api/Logs/LogRecordSeverityExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@ static class LogRecordSeverityExtensions
internal const string Fatal3ShortName = FatalShortName + "3";
internal const string Fatal4ShortName = FatalShortName + "4";

private static readonly string[] LogRecordSeverityShortNames = new string[]
{
private static readonly string[] LogRecordSeverityShortNames =
[
UnspecifiedShortName,

TraceShortName,
Expand Down Expand Up @@ -89,8 +89,8 @@ static class LogRecordSeverityExtensions
FatalShortName,
Fatal2ShortName,
Fatal3ShortName,
Fatal4ShortName,
};
Fatal4ShortName
];

/// <summary>
/// Returns the OpenTelemetry Specification short name for the <see
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public static THeaders GetHeaders<THeaders>(this OtlpExporterOptions options, Ac
{
// Specify the maximum number of substrings to return to 2
// This treats everything that follows the first `=` in the string as the value to be added for the metadata key
var keyValueData = pair.Split(new char[] { '=' }, 2);
var keyValueData = pair.Split(['='], 2);
if (keyValueData.Length != 2)
{
throw new ArgumentException("Headers provided in an invalid format.");
Expand Down Expand Up @@ -174,11 +174,11 @@ public static void TryEnableIHttpClientFactoryIntegration(this OtlpExporterOptio
"CreateClient",
BindingFlags.Public | BindingFlags.Instance,
binder: null,
new Type[] { typeof(string) },
[typeof(string)],
modifiers: null);
if (createClientMethod != null)
{
HttpClient? client = (HttpClient?)createClientMethod.Invoke(httpClientFactory, new object[] { httpClientName });
HttpClient? client = (HttpClient?)createClientMethod.Invoke(httpClientFactory, [httpClientName]);

if (client != null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public class PrometheusHttpListenerOptions
{
internal const string DefaultScrapeEndpointPath = "/metrics";

private IReadOnlyCollection<string> uriPrefixes = new[] { "http://localhost:9464/" };
private IReadOnlyCollection<string> uriPrefixes = ["http://localhost:9464/"];

/// <summary>
/// Gets or sets the path to use for the scraping endpoint. Default value: "/metrics".
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ private static BaseProcessor<Activity> BuildZipkinExporterProcessor(
"CreateClient",
BindingFlags.Public | BindingFlags.Instance,
binder: null,
new Type[] { typeof(string) },
[typeof(string)],
modifiers: null);
if (createClientMethod != null)
{
Expand Down
2 changes: 1 addition & 1 deletion src/OpenTelemetry.Extensions.Propagators/B3Propagator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public sealed class B3Propagator : TextMapPropagator
// "Debug" sampled value.
internal const string FlagsValue = "1";

private static readonly HashSet<string> AllFields = new() { XB3TraceId, XB3SpanId, XB3ParentSpanId, XB3Sampled, XB3Flags };
private static readonly HashSet<string> AllFields = [XB3TraceId, XB3SpanId, XB3ParentSpanId, XB3Sampled, XB3Flags];

private static readonly HashSet<string> SampledValues = new(StringComparer.Ordinal) { SampledValue, LegacySampledValue };

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class JaegerPropagator : TextMapPropagator
internal const string JaegerDelimiterEncoded = "%3A"; // while the spec defines the delimiter as a ':', some clients will url encode headers.
internal const string SampledValue = "1";

internal static readonly string[] JaegerDelimiters = { JaegerDelimiter, JaegerDelimiterEncoded };
internal static readonly string[] JaegerDelimiters = [JaegerDelimiter, JaegerDelimiterEncoded];

private static readonly int TraceId128BitLength = "0af7651916cd43dd8448eb211c80319c".Length;
private static readonly int SpanIdLength = "00f067aa0ba902b7".Length;
Expand Down
2 changes: 1 addition & 1 deletion src/OpenTelemetry.Shims.OpenTracing/TracerShim.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ private TextMapPropagator Propagator

foreach (var entry in textMapCarrier)
{
carrierMap.Add(entry.Key, new[] { entry.Value });
carrierMap.Add(entry.Key, [entry.Value]);
}

static IEnumerable<string>? GetCarrierKeyValue(Dictionary<string, IEnumerable<string>> source, string key)
Expand Down
8 changes: 4 additions & 4 deletions src/Shared/MathHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ namespace OpenTelemetry.Internal;
internal static class MathHelper
{
// https://en.wikipedia.org/wiki/Leading_zero
private static readonly byte[] LeadingZeroLookupTable = new byte[]
{
private static readonly byte[] LeadingZeroLookupTable =
[
8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
Expand All @@ -29,8 +29,8 @@ internal static class MathHelper
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
};
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
];

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int LeadingZero8(byte value)
Expand Down
2 changes: 1 addition & 1 deletion src/Shared/Shims/NullableAttributes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ internal sealed class MemberNotNullWhenAttribute : Attribute
public MemberNotNullWhenAttribute(bool returnValue, string member)
{
ReturnValue = returnValue;
Members = new[] { member };
Members = [member];
}

public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
Expand Down
4 changes: 2 additions & 2 deletions test/Benchmarks/Metrics/ExemplarBenchmarks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ namespace Benchmarks.Metrics;
public class ExemplarBenchmarks
{
private static readonly ThreadLocal<Random> ThreadLocalRandom = new(() => new Random());
private readonly string[] dimensionValues = new string[] { "DimVal1", "DimVal2", "DimVal3", "DimVal4", "DimVal5", "DimVal6", "DimVal7", "DimVal8", "DimVal9", "DimVal10" };
private readonly string[] dimensionValues = ["DimVal1", "DimVal2", "DimVal3", "DimVal4", "DimVal5", "DimVal6", "DimVal7", "DimVal8", "DimVal9", "DimVal10"];
private Histogram<double>? histogramWithoutTagReduction;
private Histogram<double>? histogramWithTagReduction;
private Counter<long>? counterWithoutTagReduction;
Expand Down Expand Up @@ -86,7 +86,7 @@ public void Setup()
{
return new MetricStreamConfiguration()
{
TagKeys = new string[] { "DimName1", "DimName2", "DimName3" },
TagKeys = ["DimName1", "DimName2", "DimName3"],
ExemplarReservoirFactory = CreateExemplarReservoir,
};
}
Expand Down
2 changes: 1 addition & 1 deletion test/Benchmarks/Metrics/HistogramBenchmarks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public class HistogramBenchmarks
{
private const int MaxValue = 10000;
private readonly Random random = new();
private readonly string[] dimensionValues = new string[] { "DimVal1", "DimVal2", "DimVal3", "DimVal4", "DimVal5", "DimVal6", "DimVal7", "DimVal8", "DimVal9", "DimVal10" };
private readonly string[] dimensionValues = ["DimVal1", "DimVal2", "DimVal3", "DimVal4", "DimVal5", "DimVal6", "DimVal7", "DimVal8", "DimVal9", "DimVal10"];
private Histogram<long>? histogram;
private MeterProvider? meterProvider;
private Meter? meter;
Expand Down
2 changes: 1 addition & 1 deletion test/Benchmarks/Metrics/MetricCollectBenchmarks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ namespace Benchmarks.Metrics;

public class MetricCollectBenchmarks
{
private readonly string[] dimensionValues = new string[] { "DimVal1", "DimVal2", "DimVal3", "DimVal4", "DimVal5", "DimVal6", "DimVal7", "DimVal8", "DimVal9", "DimVal10" };
private readonly string[] dimensionValues = ["DimVal1", "DimVal2", "DimVal3", "DimVal4", "DimVal5", "DimVal6", "DimVal7", "DimVal8", "DimVal9", "DimVal10"];

// TODO: Confirm if this needs to be thread-safe
private readonly Random random = new();
Expand Down
2 changes: 1 addition & 1 deletion test/Benchmarks/Metrics/MetricsBenchmarks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ namespace Benchmarks.Metrics;
public class MetricsBenchmarks
{
private readonly Random random = new();
private readonly string[] dimensionValues = new string[] { "DimVal1", "DimVal2", "DimVal3", "DimVal4", "DimVal5", "DimVal6", "DimVal7", "DimVal8", "DimVal9", "DimVal10" };
private readonly string[] dimensionValues = ["DimVal1", "DimVal2", "DimVal3", "DimVal4", "DimVal5", "DimVal6", "DimVal7", "DimVal8", "DimVal9", "DimVal10"];
private Counter<long>? counter;
private MeterProvider? meterProvider;
private Meter? meter;
Expand Down
6 changes: 3 additions & 3 deletions test/Benchmarks/Metrics/MetricsViewBenchmarks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ namespace Benchmarks.Metrics;
public class MetricsViewBenchmarks
{
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 = ["DimVal1", "DimVal2", "DimVal3", "DimVal4", "DimVal5", "DimVal6", "DimVal7", "DimVal8", "DimVal9", "DimVal10"];
private static readonly int DimensionsValuesLength = DimensionValues.Length;
private List<Metric>? metrics;
private Counter<long>? counter;
Expand Down Expand Up @@ -96,15 +96,15 @@ public void Setup()
{
this.meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(this.meter.Name)
.AddView("nomatch", new MetricStreamConfiguration() { TagKeys = new string[] { "DimName1", "DimName2", "DimName3" } })
.AddView("nomatch", new MetricStreamConfiguration() { TagKeys = ["DimName1", "DimName2", "DimName3"] })
.AddInMemoryExporter(this.metrics)
.Build();
}
else if (this.ViewConfig == ViewConfiguration.ViewApplied)
{
this.meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter(this.meter.Name)
.AddView(this.counter.Name, new MetricStreamConfiguration() { TagKeys = new string[] { "DimName1", "DimName2", "DimName3" } })
.AddView(this.counter.Name, new MetricStreamConfiguration() { TagKeys = ["DimName1", "DimName2", "DimName3"] })
.AddInMemoryExporter(this.metrics)
.Build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public class CompositePropagatorTest
count++;
if (headers.TryGetValue(name, out var value))
{
return new[] { value };
return [value];
}

return Empty;
Expand Down
8 changes: 4 additions & 4 deletions test/OpenTelemetry.Api.Tests/Trace/SpanAttributesTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,16 @@ public void ValidateAddMethods()
{
var spanAttribute = new SpanAttributes();
spanAttribute.Add("key_string", "string");
spanAttribute.Add("key_a_string", new string[] { "string" });
spanAttribute.Add("key_a_string", ["string"]);

spanAttribute.Add("key_double", 1.01);
spanAttribute.Add("key_a_double", new double[] { 1.01 });
spanAttribute.Add("key_a_double", [1.01]);

spanAttribute.Add("key_bool", true);
spanAttribute.Add("key_a_bool", new bool[] { true });
spanAttribute.Add("key_a_bool", [true]);

spanAttribute.Add("key_long", 1);
spanAttribute.Add("key_a_long", new long[] { 1 });
spanAttribute.Add("key_a_long", [1L]);

Assert.Equal(8, spanAttribute.Attributes.Count);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,6 @@ public void VerifyConsoleActivityExporterDoesntFailWithoutActivityLinkTags()

// Test that the ConsoleExporter correctly handles an Activity without Tags.
using var consoleExporter = new ConsoleActivityExporter(new ConsoleExporterOptions());
Assert.Equal(ExportResult.Success, consoleExporter.Export(new Batch<Activity>(new[] { activity }, 1)));
Assert.Equal(ExportResult.Success, consoleExporter.Export(new Batch<Activity>([activity], 1)));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1449,7 +1449,7 @@ public void LogRecordLoggerNameIsExportedWhenUsingBridgeApi(string? loggerName,

Assert.Single(logRecords);

var batch = new Batch<LogRecord>(new[] { logRecords[0] }, 1);
var batch = new Batch<LogRecord>([logRecords[0]], 1);
OtlpCollector.ExportLogsServiceRequest request = CreateLogsExportRequest(DefaultSdkLimitOptions, new ExperimentalOptions(), batch, ResourceBuilder.CreateEmpty().Build());

Assert.NotNull(request);
Expand Down Expand Up @@ -1480,7 +1480,7 @@ public void LogSerialization_ExpandsBufferForLogsAndSerializes()

Assert.Single(logRecords);

var batch = new Batch<LogRecord>(new[] { logRecords[0] }, 1);
var batch = new Batch<LogRecord>([logRecords[0]], 1);

var buffer = new byte[50];
var writePosition = ProtobufOtlpLogSerializer.WriteLogsData(ref buffer, 0, DefaultSdkLimitOptions, new(), ResourceBuilder.CreateEmpty().Build(), batch);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public void UriPrefixesInvalid()
{
Assert.Throws<ArgumentException>(() =>
{
TestPrometheusHttpListenerUriPrefixOptions(new string[] { "ftp://example.com" });
TestPrometheusHttpListenerUriPrefixOptions(["ftp://example.com"]);
});
}

Expand Down Expand Up @@ -132,7 +132,7 @@ public void PrometheusHttpListenerThrowsOnStart()
exporter,
new()
{
UriPrefixes = new string[] { address },
UriPrefixes = [address],
});

listener.Start();
Expand All @@ -158,7 +158,7 @@ public void PrometheusHttpListenerThrowsOnStart()
exporter,
new()
{
UriPrefixes = new string[] { address! },
UriPrefixes = [address!],
});

listener.Start();
Expand Down Expand Up @@ -238,7 +238,7 @@ private static MeterProvider BuildMeterProvider(Meter meter, IEnumerable<KeyValu
.ConfigureResource(x => x.Clear().AddService("my_service", serviceInstanceId: "id1").AddAttributes(attributes))
.AddPrometheusHttpListener(options =>
{
options.UriPrefixes = new string[] { generatedAddress };
options.UriPrefixes = [generatedAddress];
})
.Build();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public void ReloadOfMetricsViaIConfigurationWithExportCleanupTest(bool useWithMe

var source = new MemoryConfigurationSource();
var memory = new MemoryConfigurationProvider(source);
var configuration = new ConfigurationRoot(new[] { memory });
var configuration = new ConfigurationRoot([memory]);

using var host = MetricTestsBase.BuildHost(
useWithMetricsStyle,
Expand Down Expand Up @@ -167,7 +167,7 @@ public void ReloadOfMetricsViaIConfigurationWithoutExportCleanupTest(bool useWit
var source = new MemoryConfigurationSource();
var memory = new MemoryConfigurationProvider(source);
memory.Set($"Metrics:EnabledMetrics:{meter.Name}:Default", "true");
var configuration = new ConfigurationRoot(new[] { memory });
var configuration = new ConfigurationRoot([memory]);

using var host = MetricTestsBase.BuildHost(
useWithMetricsStyle,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ public void ExtractReturnsOriginalContextIfHeaderIsNotValid(string traceId, stri
parentSpanId,
flags);

var headers = new Dictionary<string, string[]> { { JaegerHeader, new[] { formattedHeader } } };
var headers = new Dictionary<string, string[]> { { JaegerHeader, [formattedHeader] } };

// act
var result = new JaegerPropagator().Extract(propagationContext, headers, Getter);
Expand All @@ -128,7 +128,7 @@ public void ExtractReturnsNewContextIfHeaderIsValid(string traceId, string spanI
parentSpanId,
flags);

var headers = new Dictionary<string, string[]> { { JaegerHeader, new[] { formattedHeader } } };
var headers = new Dictionary<string, string[]> { { JaegerHeader, [formattedHeader] } };

// act
var result = new JaegerPropagator().Extract(propagationContext, headers, Getter);
Expand Down
Loading
Loading