Skip to content

Commit 25871e6

Browse files
committed
fix(worker): Improve logging and handle null arguments in Worker class
1 parent 35525de commit 25871e6

File tree

2 files changed

+41
-6
lines changed

2 files changed

+41
-6
lines changed

example/ServiceDefaults/Extensions.cs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ public static class Extensions
2020

2121
public static TBuilder AddServiceDefaults<TBuilder>(this TBuilder builder) where TBuilder : IHostApplicationBuilder
2222
{
23+
ArgumentNullException.ThrowIfNull(builder);
24+
2325
builder.ConfigureOpenTelemetry();
2426

2527
builder.AddDefaultHealthChecks();
@@ -46,6 +48,8 @@ public static TBuilder AddServiceDefaults<TBuilder>(this TBuilder builder) where
4648

4749
public static TBuilder ConfigureOpenTelemetry<TBuilder>(this TBuilder builder) where TBuilder : IHostApplicationBuilder
4850
{
51+
ArgumentNullException.ThrowIfNull(builder);
52+
4953
builder.Logging.AddOpenTelemetry(logging =>
5054
{
5155
logging.IncludeFormattedMessage = true;
@@ -67,8 +71,8 @@ public static TBuilder ConfigureOpenTelemetry<TBuilder>(this TBuilder builder) w
6771
.AddAspNetCoreInstrumentation(tracing =>
6872
// Exclude health check requests from tracing
6973
tracing.Filter = context =>
70-
!context.Request.Path.StartsWithSegments(HealthEndpointPath)
71-
&& !context.Request.Path.StartsWithSegments(AlivenessEndpointPath)
74+
!context.Request.Path.StartsWithSegments(HealthEndpointPath, StringComparison.OrdinalIgnoreCase)
75+
&& !context.Request.Path.StartsWithSegments(AlivenessEndpointPath, StringComparison.OrdinalIgnoreCase)
7276
)
7377
// Uncomment the following line to enable gRPC instrumentation (requires the OpenTelemetry.Instrumentation.GrpcNetClient package)
7478
//.AddGrpcClientInstrumentation()
@@ -102,6 +106,8 @@ private static TBuilder AddOpenTelemetryExporters<TBuilder>(this TBuilder builde
102106

103107
public static TBuilder AddDefaultHealthChecks<TBuilder>(this TBuilder builder) where TBuilder : IHostApplicationBuilder
104108
{
109+
ArgumentNullException.ThrowIfNull(builder);
110+
105111
builder.Services.AddHealthChecks()
106112
// Add a default liveness check to ensure app is responsive
107113
.AddCheck("self", () => HealthCheckResult.Healthy(), ["live"]);
@@ -111,6 +117,8 @@ public static TBuilder AddDefaultHealthChecks<TBuilder>(this TBuilder builder) w
111117

112118
public static WebApplication MapDefaultEndpoints(this WebApplication app)
113119
{
120+
ArgumentNullException.ThrowIfNull(app);
121+
114122
// Adding health checks endpoints to applications in non-development environments has security implications.
115123
// See https://aka.ms/dotnet/aspire/healthchecks for details before enabling these endpoints in non-development environments.
116124
if (app.Environment.IsDevelopment())

example/WorkerService/Worker.cs

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33

44
namespace WorkerService;
55

6-
internal class Worker : BackgroundService
6+
#pragma warning disable CA1812 // False-positive: Class is instantiated by the generic host
7+
internal sealed partial class Worker : BackgroundService
8+
#pragma warning restore CA1812 // False-positive: Class is instantiated by the generic host
79
{
810
private readonly ILogger<Worker> _logger;
911

@@ -27,21 +29,46 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
2729
{
2830
using IServiceScope scope = _serviceProvider.CreateScope();
2931
ILdapConnection ldapConnection = scope.ServiceProvider.GetRequiredService<ILdapConnection>();
30-
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
32+
Log.WorkerRunning(_logger, DateTimeOffset.Now);
3133
DirectoryResponse r = ldapConnection.SendRequest(new SearchRequest(
3234
"dc=example,dc=com",
3335
"(objectClass=*)",
3436
SearchScope.Subtree,
3537
"cn", "sn", "mail"));
36-
_logger.LogInformation("LDAP response: {response}", r);
38+
Log.LdapResponse(_logger, r);
3739
}
40+
#pragma warning disable CA1031 // Catching general exception to log it
3841
catch (Exception ex)
42+
#pragma warning restore CA1031 // Catching general exception to log it
3943
{
40-
_logger.LogError(ex, "An error occurred while connecting to LDAP");
44+
Log.LdapError(_logger, ex);
4145
}
4246
}
4347

4448
await Task.Delay(1000, stoppingToken).ConfigureAwait(false);
4549
}
4650
}
51+
52+
internal static partial class Log
53+
{
54+
[LoggerMessage(
55+
EventId = 0,
56+
Level = LogLevel.Information,
57+
Message = "Worker running at: {Time}")]
58+
public static partial void WorkerRunning(
59+
ILogger logger, DateTimeOffset time);
60+
61+
[LoggerMessage(
62+
EventId = 1,
63+
Level = LogLevel.Information,
64+
Message = "LDAP response: {Response}")]
65+
public static partial void LdapResponse(
66+
ILogger logger, [LogProperties] DirectoryResponse response);
67+
68+
[LoggerMessage(
69+
EventId = 2,
70+
Level = LogLevel.Error,
71+
Message = "An error occurred while connecting to LDAP")]
72+
public static partial void LdapError(ILogger logger, Exception? exception = null);
73+
}
4774
}

0 commit comments

Comments
 (0)