Skip to content

Commit cfbee7a

Browse files
authored
Enable Roslyn analysis - StartupHook (#4665)
* StartupHook - enable analysis * CA1035 * CA1309 * CA1310 * CA1806 * CA2201 * CA2201 * CA1859 * Mute CA1031 on the project level
1 parent 8fd2379 commit cfbee7a

File tree

6 files changed

+41
-16
lines changed

6 files changed

+41
-16
lines changed

src/OpenTelemetry.AutoInstrumentation.StartupHook/OpenTelemetry.AutoInstrumentation.StartupHook.csproj

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66
Reference: https://github.com/open-telemetry/opentelemetry-dotnet-instrumentation/issues/1644 -->
77
<TargetFrameworks>netcoreapp3.1</TargetFrameworks>
88
<Description>StartupHook used by the OpenTelemetry.AutoInstrumentation project.</Description>
9+
<!-- Suppress CA1031 warnings about catching general exception types. In this project we need to catch all exceptions to prevent the application from crashing. -->
10+
<NoWarn>$(NoWarn);CA1031</NoWarn>
11+
<AnalysisLevel>latest-All</AnalysisLevel>
912
</PropertyGroup>
1013

1114
<ItemGroup>

src/OpenTelemetry.AutoInstrumentation.StartupHook/RulesEngine/ApplicationInExcludeListRule.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ public ApplicationInExcludeListRule()
2020
internal override bool Evaluate()
2121
{
2222
var appDomainName = GetAppDomainName();
23-
if (appDomainName.Equals("dotnet", StringComparison.InvariantCultureIgnoreCase))
23+
if (appDomainName.Equals("dotnet", StringComparison.OrdinalIgnoreCase))
2424
{
2525
Logger.Information($"Rule Engine: AppDomain name is dotnet. Skipping initialization.");
2626
return false;
@@ -65,7 +65,7 @@ private static string GetAppDomainName()
6565
}
6666
}
6767

68-
private static ICollection<string> GetExcludedApplicationNames()
68+
private static List<string> GetExcludedApplicationNames()
6969
{
7070
var excludedProcesses = new List<string>();
7171

src/OpenTelemetry.AutoInstrumentation.StartupHook/RulesEngine/AssemblyFileVersionRule.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ internal override bool Evaluate()
6161
}
6262
catch (Exception ex)
6363
{
64-
// Exception in rule evaluation should not impact the result of the rule.
64+
// An exception in rule evaluation should not impact the result of the rule.
6565
Logger.Warning($"Rule Engine: Couldn't evaluate assembly reference file version. Exception: {ex}");
6666
}
6767

src/OpenTelemetry.AutoInstrumentation.StartupHook/StartupHook.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ internal class StartupHook
2323
/// </summary>
2424
public static void Initialize()
2525
{
26-
bool.TryParse(Environment.GetEnvironmentVariable(ConfigurationKeys.FailFast), out var failFast);
26+
_ = bool.TryParse(Environment.GetEnvironmentVariable(ConfigurationKeys.FailFast), out var failFast);
2727

2828
try
2929
{
@@ -32,7 +32,7 @@ public static void Initialize()
3232
var ruleEngine = new RuleEngine();
3333
if (!ruleEngine.ValidateRules())
3434
{
35-
throw new Exception(
35+
throw new InvalidOperationException(
3636
"Rule Engine Failure: One or more rules failed validation. Automatic Instrumentation won't be loaded.");
3737
}
3838

@@ -47,7 +47,7 @@ public static void Initialize()
4747
{
4848
if (failFast)
4949
{
50-
throw new Exception("StartupHook failed to create an instance of the Loader");
50+
throw new InvalidOperationException("StartupHook failed to create an instance of the Loader");
5151
}
5252
}
5353
else
@@ -74,15 +74,15 @@ private static string GetLoaderAssemblyLocation()
7474
try
7575
{
7676
var startupAssemblyFilePath = Assembly.GetExecutingAssembly().Location;
77-
if (startupAssemblyFilePath.StartsWith(@"\\?\"))
77+
if (startupAssemblyFilePath.StartsWith(@"\\?\", StringComparison.Ordinal))
7878
{
7979
// This will only be used in case the local path exceeds max_path size limit
8080
startupAssemblyFilePath = startupAssemblyFilePath.Substring(4);
8181
}
8282

8383
// StartupHook and Loader assemblies are in the same path
8484
var startupAssemblyDirectoryPath = Path.GetDirectoryName(startupAssemblyFilePath) ??
85-
throw new NullReferenceException("StartupAssemblyFilePath is NULL");
85+
throw new InvalidOperationException("StartupAssemblyFilePath is NULL");
8686
return startupAssemblyDirectoryPath;
8787
}
8888
catch (Exception ex)

src/OpenTelemetry.AutoInstrumentation/Logging/InternalLogger.cs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
// Copyright The OpenTelemetry Authors
22
// SPDX-License-Identifier: Apache-2.0
33

4+
using System.Globalization;
5+
46
namespace OpenTelemetry.AutoInstrumentation.Logging;
57

68
internal class InternalLogger : IOtelLogger
@@ -214,7 +216,7 @@ private void WriteImpl(LogLevel level, Exception? exception, string messageTempl
214216
try
215217
{
216218
// Use template if no arguments provided, otherwise format the template with provided arguments.
217-
var rawMessage = args == NoPropertyValues ? messageTemplate : string.Format(messageTemplate, args);
219+
var rawMessage = args == NoPropertyValues ? messageTemplate : string.Format(CultureInfo.InvariantCulture, messageTemplate, args);
218220
if (exception != null)
219221
{
220222
rawMessage += $"{Environment.NewLine}Exception: {exception.Message}{Environment.NewLine}{exception}";
@@ -226,7 +228,9 @@ private void WriteImpl(LogLevel level, Exception? exception, string messageTempl
226228
WriteEventSourceLog(level, rawMessage);
227229
}
228230
}
229-
catch
231+
#pragma warning disable CA1031 // Do not catch general exception
232+
catch (Exception)
233+
#pragma warning restore CA1031 // Do not catch general exception
230234
{
231235
try
232236
{
@@ -236,7 +240,9 @@ private void WriteImpl(LogLevel level, Exception? exception, string messageTempl
236240
: "; " + string.Join(", ", args);
237241
Console.Error.WriteLine($"{messageTemplate}{properties}{ex}");
238242
}
239-
catch
243+
#pragma warning disable CA1031 // Do not catch general exception
244+
catch (Exception)
245+
#pragma warning restore CA1031 // Do not catch general exception
240246
{
241247
// ignore
242248
}

src/OpenTelemetry.AutoInstrumentation/Logging/OtelLogging.cs

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,9 @@ public static void CloseLogger(string suffix, IOtelLogger otelLogger)
5454
otelLogger.Close();
5555
}
5656
}
57+
#pragma warning disable CA1031 // Do not catch general exception
5758
catch (Exception)
59+
#pragma warning restore CA1031 // Do not catch general exception
5860
{
5961
// intentionally empty
6062
}
@@ -85,7 +87,9 @@ internal static void Reset()
8587
_ => logLevel
8688
};
8789
}
90+
#pragma warning disable CA1031 // Do not catch general exception
8891
catch (Exception)
92+
#pragma warning restore CA1031 // Do not catch general exception
8993
{
9094
// theoretically, can happen when process has no privileges to check env
9195
}
@@ -110,7 +114,9 @@ internal static LogSink GetConfiguredLogSink()
110114
_ => logSink
111115
};
112116
}
117+
#pragma warning disable CA1031 // Do not catch general exception
113118
catch (Exception)
119+
#pragma warning restore CA1031 // Do not catch general exception
114120
{
115121
// theoretically, can happen when process has no privileges to check env
116122
}
@@ -132,7 +138,9 @@ internal static long GetConfiguredFileSizeLimitBytes()
132138

133139
return long.TryParse(configuredFileSizeLimit, out var limit) && limit > 0 ? limit : defaultFileSizeLimitBytes;
134140
}
141+
#pragma warning disable CA1031 // Do not catch general exception
135142
catch (Exception)
143+
#pragma warning restore CA1031 // Do not catch general exception
136144
{
137145
// theoretically, can happen when process has no privileges to check env
138146
return defaultFileSizeLimitBytes;
@@ -154,7 +162,7 @@ private static IOtelLogger CreateLogger(string suffix)
154162
private static ISink CreateSink(string suffix)
155163
{
156164
// Uses ISink? here, sink creation can fail so we specify default fallback at the end.
157-
var sink = _configuredLogSink switch
165+
ISink? sink = _configuredLogSink switch
158166
{
159167
LogSink.NoOp => NoopSink.Instance,
160168
LogSink.Console => new ConsoleSink(suffix),
@@ -168,7 +176,7 @@ private static ISink CreateSink(string suffix)
168176
NoopSink.Instance;
169177
}
170178

171-
private static ISink? CreateFileSink(string suffix)
179+
private static PeriodicFlushToDiskSink? CreateFileSink(string suffix)
172180
{
173181
try
174182
{
@@ -188,7 +196,9 @@ private static ISink CreateSink(string suffix)
188196
return new PeriodicFlushToDiskSink(rollingFileSink, TimeSpan.FromSeconds(5));
189197
}
190198
}
199+
#pragma warning disable CA1031 // Do not catch general exception
191200
catch (Exception)
201+
#pragma warning restore CA1031 // Do not catch general exception
192202
{
193203
// unable to configure logging to a file
194204
}
@@ -208,7 +218,9 @@ private static string GetLogFileName(string suffix)
208218
? $"otel-dotnet-auto-{process.Id}-{appDomainName}-.log"
209219
: $"otel-dotnet-auto-{process.Id}-{appDomainName}-{suffix}-.log";
210220
}
211-
catch
221+
#pragma warning disable CA1031 // Do not catch general exception
222+
catch (Exception)
223+
#pragma warning restore CA1031 // Do not catch general exception
212224
{
213225
// We can't get the process info
214226
return string.IsNullOrEmpty(suffix)
@@ -250,7 +262,9 @@ private static string GetEncodedAppDomainName()
250262

251263
logDirectory = CreateDirectoryIfMissing(logDirectory) ?? Path.GetTempPath();
252264
}
253-
catch
265+
#pragma warning disable CA1031 // Do not catch general exception
266+
catch (Exception)
267+
#pragma warning restore CA1031 // Do not catch general exception
254268
{
255269
// The try block may throw a SecurityException if not granted the System.Security.Permissions.FileIOPermission
256270
// because of the following API calls
@@ -272,7 +286,9 @@ private static string GetEncodedAppDomainName()
272286
Directory.CreateDirectory(pathToCreate);
273287
return pathToCreate;
274288
}
275-
catch
289+
#pragma warning disable CA1031 // Do not catch general exception
290+
catch (Exception)
291+
#pragma warning restore CA1031 // Do not catch general exception
276292
{
277293
// Unable to create the directory meaning that the user will have to create it on their own.
278294
// It is unsafe to log here, so return null to defer deciding what the path is

0 commit comments

Comments
 (0)