Skip to content

Commit e8e2032

Browse files
committed
Fix: Better SeriLog Override
1 parent 9f01a2e commit e8e2032

File tree

5 files changed

+27
-60
lines changed

5 files changed

+27
-60
lines changed

src/CodeOfChaos.Extensions.AspNetCore/LoggingOverrideExtensions.cs

Lines changed: 4 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@
33
// ---------------------------------------------------------------------------------------------------------------------
44
using Microsoft.AspNetCore.Builder;
55
using Microsoft.Extensions.DependencyInjection;
6-
using Microsoft.Extensions.Hosting;
76
using Microsoft.Extensions.Logging;
87
using Serilog;
98
using Serilog.Core;
9+
using ILogger=Serilog.ILogger;
1010

1111
namespace CodeOfChaos.Extensions.AspNetCore;
1212
// ---------------------------------------------------------------------------------------------------------------------
@@ -33,24 +33,12 @@ public static WebApplicationBuilder OverrideLoggingWithSerilog(
3333
configure?.Invoke(loggerConfig);
3434

3535
Log.Logger = loggerConfig.CreateLogger();
36-
37-
36+
3837
// Clear default providers and setup Serilog
3938
builder.Logging.ClearProviders();
40-
builder.Logging.AddSerilog(Log.Logger);
41-
builder.Services.AddSingleton(Log.Logger);
42-
43-
builder.Services.AddHostedService<ApplicationShutdownLoggerCleanup>(); // Ensure cleanup
4439
builder.Services.AddLogging(loggingBuilder => loggingBuilder.AddSerilog(Log.Logger));
45-
40+
builder.Services.AddSingleton(Log.Logger);
41+
4642
return builder;
4743
}
48-
49-
public class ApplicationShutdownLoggerCleanup : IHostedService {
50-
public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask;
51-
52-
public async Task StopAsync(CancellationToken cancellationToken) {
53-
await Log.CloseAndFlushAsync();
54-
}
55-
}
5644
}

src/CodeOfChaos.Extensions.Serilog/ConsoleFormats.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,5 @@ namespace CodeOfChaos.Extensions.Serilog;
88
public static class ConsoleOutputTemplates {
99
public const string Default = "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}";
1010
public const string DefaultShort = "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}";
11-
public const string AnnaSasDevServer = "[{Timestamp:HH:mm:ss} {Level:u3} {Section,-8}] {Message:lj}{NewLine}";
11+
public const string AnnaSasDevServer = "[{Timestamp:HH:mm:ss} {Level:u3} {Section,-12}] {Message:lj}{NewLine}";
1212
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// ---------------------------------------------------------------------------------------------------------------------
2+
// Imports
3+
// ---------------------------------------------------------------------------------------------------------------------
4+
using Serilog.Core;
5+
using Serilog.Events;
6+
7+
namespace CodeOfChaos.Extensions.Serilog.Enrichers;
8+
// ---------------------------------------------------------------------------------------------------------------------
9+
// Code
10+
// ---------------------------------------------------------------------------------------------------------------------
11+
// Define your section here (e.g., "auth" or "db")
12+
public class SectionEnricher(string sectionName) : ILogEventEnricher {
13+
public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) {
14+
LogEventProperty sectionProperty = propertyFactory.CreateProperty("Section", sectionName);
15+
logEvent.AddPropertyIfAbsent(sectionProperty);
16+
}
17+
}

src/CodeOfChaos.Extensions.Serilog/LoggerConfigurationExtensions.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
// ---------------------------------------------------------------------------------------------------------------------
44
using CodeOfChaos.Extensions.Serilog;
55
using CodeOfChaos.Extensions.Serilog.Enrichers;
6+
using Serilog.Configuration;
67
using Serilog.Core;
78
using Serilog.Events;
89
using Serilog.Sinks.SystemConsole.Themes;
@@ -43,12 +44,16 @@ public static LoggerConfiguration WithPaddedSectionEnricher(this LoggerConfigura
4344

4445
public static LoggerConfiguration WithTruncateSourceContextEnricher(this LoggerConfiguration loggerConfiguration, int maxLength = 8)
4546
=> loggerConfiguration.Enrich.With(new TruncateSourceContextEnricher(maxLength));
47+
48+
public static LoggerConfiguration WithSectionEnricher(this LoggerConfiguration loggerConfiguration, string? defaultSection = null)
49+
=> loggerConfiguration.Enrich.With(new SectionEnricher(defaultSection ?? string.Empty));
4650

4751
// -----------------------------------------------------------------------------------------------------------------
4852
// Opinionated configurations
4953
// -----------------------------------------------------------------------------------------------------------------
5054
public static LoggerConfiguration AsAnnaSasDevServerConsole(this LoggerConfiguration loggerConfiguration) =>
5155
loggerConfiguration
56+
.WithSectionEnricher()
5257
.WithPaddedSectionEnricher(maxLength: 12)
5358
.WriteToAsyncConsole(
5459
outputTemplate: ConsoleOutputTemplates.AnnaSasDevServer,

tests/Tests.CodeOfChaos.Extensions.AspNetCore/LoggingOverrideExtensionTests.cs

Lines changed: 0 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -76,49 +76,6 @@ await Assert.That(logger)
7676
.IsNotNull()
7777
.Because("Serilog should replace the existing providers when overriding logging.");
7878
}
79-
80-
[Test]
81-
public async Task OverrideLoggingWithSerilog_ShouldRegisterApplicationShutdownCleanupService() {
82-
// Arrange
83-
WebApplicationBuilder builder = WebApplication.CreateBuilder();
84-
85-
// Act
86-
builder.OverrideLoggingWithSerilog();
87-
88-
// Assert
89-
ServiceProvider serviceProvider = builder.Services.BuildServiceProvider();
90-
IEnumerable<IHostedService> hostedServices = serviceProvider.GetServices<IHostedService>().ToArray();
91-
await Assert.That(hostedServices).IsNotNull().Because("IHostedService collection should be available.");
92-
await Assert.That(hostedServices.Any(service => service is LoggingOverrideExtensions.ApplicationShutdownLoggerCleanup)).IsTrue().Because("There should be at least one hosted service.");
93-
}
94-
95-
[Test]
96-
public async Task ApplicationShutdownLoggerCleanup_ShouldFlushLogsOnStop() {
97-
// Arrange
98-
var cleanupService = new LoggingOverrideExtensions.ApplicationShutdownLoggerCleanup();
99-
bool flushCalled = false;
100-
101-
// Replace the static Serilog Logger with a mock logger
102-
ILogger originalLogger = Log.Logger;
103-
Log.Logger = new LoggerConfiguration()
104-
.WriteTo.Sink(new DelegatingSink(_ => flushCalled = true))// Custom sink to detect flush calls
105-
.CreateLogger();
106-
107-
108-
// Act
109-
Log.Logger.Information("Test log message");// Log a message to verify it is flushed
110-
111-
await cleanupService.StartAsync(CancellationToken.None);
112-
await cleanupService.StopAsync(CancellationToken.None);
113-
114-
// Assert
115-
await Assert.That(flushCalled)
116-
.IsTrue()
117-
.Because("Log.CloseAndFlush should be triggered when the application stops.");
118-
119-
// Just to be sure
120-
Log.Logger = originalLogger;// Restore the original logger
121-
}
12279
}
12380

12481
// ---------------------------------------------------------------------------------------------------------------------

0 commit comments

Comments
 (0)