Skip to content

Commit f183a6a

Browse files
[Examples.Console] enable analysis (#6221)
Co-authored-by: Rajkumar Rangaraj <rajrang@microsoft.com>
1 parent 72f7348 commit f183a6a

15 files changed

+81
-66
lines changed

examples/Console/Examples.Console.csproj

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1-
<Project Sdk="Microsoft.NET.Sdk">
1+
<Project Sdk="Microsoft.NET.Sdk">
22

33
<PropertyGroup>
44
<OutputType>Exe</OutputType>
55
<TargetFramework>$(DefaultTargetFrameworkForExampleApps)</TargetFramework>
6-
<NoWarn>$(NoWarn),CS0618</NoWarn>
6+
<NoWarn>$(NoWarn),CA1812</NoWarn>
7+
<AnalysisLevel>latest-all</AnalysisLevel>
78
</PropertyGroup>
89

910
<ItemGroup>

examples/Console/InstrumentationWithActivitySource.cs

+5-5
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
namespace Examples.Console;
1010

11-
internal class InstrumentationWithActivitySource : IDisposable
11+
internal sealed class InstrumentationWithActivitySource : IDisposable
1212
{
1313
private const string RequestPath = "/api/request";
1414
private readonly SampleServer server = new();
@@ -27,7 +27,7 @@ public void Dispose()
2727
this.server.Dispose();
2828
}
2929

30-
private class SampleServer : IDisposable
30+
private sealed class SampleServer : IDisposable
3131
{
3232
private readonly HttpListener listener = new();
3333

@@ -66,7 +66,7 @@ public void Start(string url)
6666
}
6767

6868
activity?.SetTag("request.content", requestContent);
69-
activity?.SetTag("request.length", requestContent.Length.ToString());
69+
activity?.SetTag("request.length", requestContent.Length);
7070

7171
var echo = Encoding.UTF8.GetBytes("echo: " + requestContent);
7272
context.Response.ContentEncoding = Encoding.UTF8;
@@ -88,7 +88,7 @@ public void Dispose()
8888
}
8989
}
9090

91-
private class SampleClient : IDisposable
91+
private sealed class SampleClient : IDisposable
9292
{
9393
private CancellationTokenSource? cts;
9494
private Task? requestTask;
@@ -114,7 +114,7 @@ public void Start(string url)
114114
count++;
115115

116116
activity?.AddEvent(new ActivityEvent("PostAsync:Started"));
117-
using var response = await client.PostAsync(url, content, cancellationToken).ConfigureAwait(false);
117+
using var response = await client.PostAsync(new Uri(url, UriKind.Absolute), content, cancellationToken).ConfigureAwait(false);
118118
activity?.AddEvent(new ActivityEvent("PostAsync:Ended"));
119119

120120
activity?.SetTag("http.status_code", (int)response.StatusCode);

examples/Console/Program.cs

+12-12
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ namespace Examples.Console;
88
/// <summary>
99
/// Main samples entry point.
1010
/// </summary>
11-
public class Program
11+
internal static class Program
1212
{
1313
/// <summary>
1414
/// Main method - invoke this using command line.
@@ -51,21 +51,21 @@ public static void Main(string[] args)
5151
#pragma warning disable SA1402 // File may only contain a single type
5252

5353
[Verb("zipkin", HelpText = "Specify the options required to test Zipkin exporter")]
54-
internal class ZipkinOptions
54+
internal sealed class ZipkinOptions
5555
{
5656
[Option('u', "uri", HelpText = "Please specify the uri of Zipkin backend", Required = true)]
5757
public required string Uri { get; set; }
5858
}
5959

6060
[Verb("prometheus", HelpText = "Specify the options required to test Prometheus")]
61-
internal class PrometheusOptions
61+
internal sealed class PrometheusOptions
6262
{
6363
[Option('p', "port", Default = 9464, HelpText = "The port to expose metrics. The endpoint will be http://localhost:port/metrics/ (this is the port from which your Prometheus server scraps metrics from.)", Required = false)]
6464
public int Port { get; set; }
6565
}
6666

6767
[Verb("metrics", HelpText = "Specify the options required to test Metrics")]
68-
internal class MetricsOptions
68+
internal sealed class MetricsOptions
6969
{
7070
[Option('d', "IsDelta", HelpText = "Export Delta metrics", Required = false, Default = false)]
7171
public bool IsDelta { get; set; }
@@ -93,32 +93,32 @@ internal class MetricsOptions
9393
}
9494

9595
[Verb("grpc", HelpText = "Specify the options required to test Grpc.Net.Client")]
96-
internal class GrpcNetClientOptions
96+
internal sealed class GrpcNetClientOptions
9797
{
9898
}
9999

100100
[Verb("httpclient", HelpText = "Specify the options required to test HttpClient")]
101-
internal class HttpClientOptions
101+
internal sealed class HttpClientOptions
102102
{
103103
}
104104

105105
[Verb("console", HelpText = "Specify the options required to test console exporter")]
106-
internal class ConsoleOptions
106+
internal sealed class ConsoleOptions
107107
{
108108
}
109109

110110
[Verb("otelshim", HelpText = "Specify the options required to test OpenTelemetry Shim with console exporter")]
111-
internal class OpenTelemetryShimOptions
111+
internal sealed class OpenTelemetryShimOptions
112112
{
113113
}
114114

115115
[Verb("opentracing", HelpText = "Specify the options required to test OpenTracing Shim with console exporter")]
116-
internal class OpenTracingShimOptions
116+
internal sealed class OpenTracingShimOptions
117117
{
118118
}
119119

120120
[Verb("otlp", HelpText = "Specify the options required to test OpenTelemetry Protocol (OTLP)")]
121-
internal class OtlpOptions
121+
internal sealed class OtlpOptions
122122
{
123123
[Option('e', "endpoint", HelpText = "Target to which the exporter is going to send traces (default value depends on protocol).", Default = null)]
124124
public string? Endpoint { get; set; }
@@ -128,7 +128,7 @@ internal class OtlpOptions
128128
}
129129

130130
[Verb("logs", HelpText = "Specify the options required to test Logs")]
131-
internal class LogsOptions
131+
internal sealed class LogsOptions
132132
{
133133
[Option("useExporter", Default = "otlp", HelpText = "Options include otlp or console.", Required = false)]
134134
public string? UseExporter { get; set; }
@@ -147,7 +147,7 @@ internal class LogsOptions
147147
}
148148

149149
[Verb("inmemory", HelpText = "Specify the options required to test InMemory Exporter")]
150-
internal class InMemoryOptions
150+
internal sealed class InMemoryOptions
151151
{
152152
}
153153

examples/Console/TestConsoleExporter.cs

+10-10
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
namespace Examples.Console;
1010

11-
internal class TestConsoleExporter
11+
internal sealed class TestConsoleExporter
1212
{
1313
// To run this example, run the following command from
1414
// the reporoot\examples\Console\.
@@ -27,21 +27,21 @@ private static int RunWithActivitySource()
2727
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
2828
.AddSource("Samples.SampleClient", "Samples.SampleServer")
2929
.ConfigureResource(res => res.AddService("console-test"))
30+
#pragma warning disable CA2000 // Dispose objects before losing scope
3031
.AddProcessor(new MyProcessor()) // This must be added before ConsoleExporter
32+
#pragma warning restore CA2000 // Dispose objects before losing scope
3133
.AddConsoleExporter()
3234
.Build();
3335

3436
// The above line is required only in applications
3537
// which decide to use OpenTelemetry.
36-
using (var sample = new InstrumentationWithActivitySource())
37-
{
38-
sample.Start();
38+
using var sample = new InstrumentationWithActivitySource();
39+
sample.Start();
3940

40-
System.Console.WriteLine("Traces are being created and exported " +
41-
"to Console in the background. " +
42-
"Press ENTER to stop.");
43-
System.Console.ReadLine();
44-
}
41+
System.Console.WriteLine("Traces are being created and exported " +
42+
"to Console in the background. " +
43+
"Press ENTER to stop.");
44+
System.Console.ReadLine();
4545

4646
return 0;
4747
}
@@ -50,7 +50,7 @@ private static int RunWithActivitySource()
5050
/// An example of custom processor which
5151
/// can be used to add more tags to an activity.
5252
/// </summary>
53-
internal class MyProcessor : BaseProcessor<Activity>
53+
internal sealed class MyProcessor : BaseProcessor<Activity>
5454
{
5555
public override void OnStart(Activity activity)
5656
{

examples/Console/TestGrpcNetClient.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
namespace Examples.Console;
1212

13-
internal class TestGrpcNetClient
13+
internal sealed class TestGrpcNetClient
1414
{
1515
internal static int Run(GrpcNetClientOptions options)
1616
{

examples/Console/TestHttpClient.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
namespace Examples.Console;
1010

11-
internal class TestHttpClient
11+
internal sealed class TestHttpClient
1212
{
1313
// To run this example, run the following command from
1414
// the reporoot\examples\Console\.
@@ -32,7 +32,7 @@ internal static int Run(HttpClientOptions options)
3232
using (var parent = source.StartActivity("incoming request", ActivityKind.Server))
3333
{
3434
using var client = new HttpClient();
35-
client.GetStringAsync("http://bing.com").GetAwaiter().GetResult();
35+
client.GetStringAsync(new Uri("http://bing.com", UriKind.Absolute)).GetAwaiter().GetResult();
3636
}
3737

3838
System.Console.WriteLine("Press Enter key to exit.");

examples/Console/TestInMemoryExporter.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
namespace Examples.Console;
1010

11-
internal class TestInMemoryExporter
11+
internal sealed class TestInMemoryExporter
1212
{
1313
// To run this example, run the following command from
1414
// the reporoot\examples\Console\.

examples/Console/TestLogs.cs

+5-5
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
namespace Examples.Console;
99

10-
internal class TestLogs
10+
internal sealed class TestLogs
1111
{
1212
internal static int Run(LogsOptions options)
1313
{
@@ -112,11 +112,11 @@ internal static int Run(LogsOptions options)
112112
});
113113
});
114114

115-
var logger = loggerFactory.CreateLogger<Program>();
116-
using (logger.BeginScope("{city}", "Seattle"))
117-
using (logger.BeginScope("{storeType}", "Physical"))
115+
var logger = loggerFactory.CreateLogger<TestLogs>();
116+
using (logger.BeginCityScope("Seattle"))
117+
using (logger.BeginStoreTypeScope("Physical"))
118118
{
119-
logger.LogInformation("Hello from {name} {price}.", "tomato", 2.99);
119+
logger.HelloFrom("tomato", 2.99);
120120
}
121121

122122
return 0;
+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// Copyright The OpenTelemetry Authors
2+
// SPDX-License-Identifier: Apache-2.0
3+
4+
using Microsoft.Extensions.Logging;
5+
6+
namespace Examples.Console;
7+
8+
internal static partial class TestLogsExtensions
9+
{
10+
private static readonly Func<ILogger, string, IDisposable?> CityScope = LoggerMessage.DefineScope<string>("{City}");
11+
private static readonly Func<ILogger, string, IDisposable?> StoreTypeScope = LoggerMessage.DefineScope<string>("{StoreType}");
12+
13+
public static IDisposable? BeginCityScope(this ILogger logger, string city) => CityScope(logger, city);
14+
15+
public static IDisposable? BeginStoreTypeScope(this ILogger logger, string storeType) => StoreTypeScope(logger, storeType);
16+
17+
[LoggerMessage(LogLevel.Information, "Hello from {Name} {Price}.")]
18+
public static partial void HelloFrom(this ILogger logger, string name, double price);
19+
}

examples/Console/TestMetrics.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
namespace Examples.Console;
1212

13-
internal class TestMetrics
13+
internal sealed class TestMetrics
1414
{
1515
internal static int Run(MetricsOptions options)
1616
{
@@ -97,7 +97,7 @@ internal static int Run(MetricsOptions options)
9797
{
9898
return new List<Measurement<int>>()
9999
{
100-
new Measurement<int>(
100+
new(
101101
(int)Process.GetCurrentProcess().PrivateMemorySize64,
102102
new KeyValuePair<string, object?>("tag1", "value1")),
103103
};

examples/Console/TestOTelShimWithConsoleExporter.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
namespace Examples.Console;
99

10-
internal class TestOTelShimWithConsoleExporter
10+
internal sealed class TestOTelShimWithConsoleExporter
1111
{
1212
internal static int Run(OpenTelemetryShimOptions options)
1313
{

examples/Console/TestOpenTracingShim.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
namespace Examples.Console;
1212

13-
internal class TestOpenTracingShim
13+
internal sealed class TestOpenTracingShim
1414
{
1515
internal static int Run(OpenTracingShimOptions options)
1616
{

examples/Console/TestOtlpExporter.cs

+9-11
Original file line numberDiff line numberDiff line change
@@ -69,24 +69,22 @@ private static int RunWithActivitySource(OtlpOptions options)
6969

7070
// The above line is required only in Applications
7171
// which decide to use OpenTelemetry.
72-
using (var sample = new InstrumentationWithActivitySource())
73-
{
74-
sample.Start();
72+
using var sample = new InstrumentationWithActivitySource();
73+
sample.Start();
7574

76-
System.Console.WriteLine("Traces are being created and exported " +
77-
"to the OpenTelemetry Collector in the background. " +
78-
"Press ENTER to stop.");
79-
System.Console.ReadLine();
80-
}
75+
System.Console.WriteLine("Traces are being created and exported " +
76+
"to the OpenTelemetry Collector in the background. " +
77+
"Press ENTER to stop.");
78+
System.Console.ReadLine();
8179

8280
return 0;
8381
}
8482

8583
private static OtlpExportProtocol? ToOtlpExportProtocol(string? protocol) =>
86-
protocol?.Trim().ToLower() switch
84+
protocol?.Trim().ToUpperInvariant() switch
8785
{
88-
"grpc" => OtlpExportProtocol.Grpc,
89-
"http/protobuf" => OtlpExportProtocol.HttpProtobuf,
86+
"GRPC" => OtlpExportProtocol.Grpc,
87+
"HTTP/PROTOBUF" => OtlpExportProtocol.HttpProtobuf,
9088
_ => null,
9189
};
9290
}

examples/Console/TestPrometheusExporter.cs

+3-4
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,18 @@
33

44
using System.Diagnostics;
55
using System.Diagnostics.Metrics;
6+
using System.Security.Cryptography;
67
using OpenTelemetry;
78
using OpenTelemetry.Metrics;
8-
using OpenTelemetry.Trace;
99

1010
namespace Examples.Console;
1111

12-
internal class TestPrometheusExporter
12+
internal sealed class TestPrometheusExporter
1313
{
1414
private static readonly Meter MyMeter = new("MyMeter");
1515
private static readonly Meter MyMeter2 = new("MyMeter2");
1616
private static readonly Counter<double> Counter = MyMeter.CreateCounter<double>("myCounter", description: "A counter for demonstration purpose.");
1717
private static readonly Histogram<long> MyHistogram = MyMeter.CreateHistogram<long>("myHistogram");
18-
private static readonly ThreadLocal<Random> ThreadLocalRandom = new(() => new Random());
1918

2019
internal static int Run(PrometheusOptions options)
2120
{
@@ -57,7 +56,7 @@ internal static int Run(PrometheusOptions options)
5756
{
5857
Counter.Add(9.9, new("name", "apple"), new("color", "red"));
5958
Counter.Add(99.9, new("name", "lemon"), new("color", "yellow"));
60-
MyHistogram.Record(ThreadLocalRandom.Value!.Next(1, 1500), new("tag1", "value1"), new("tag2", "value2"));
59+
MyHistogram.Record(RandomNumberGenerator.GetInt32(1, 1500), new("tag1", "value1"), new("tag2", "value2"));
6160
Task.Delay(10).Wait();
6261
}
6362
});

0 commit comments

Comments
 (0)