Skip to content

Commit

Permalink
Fix the serilog bug (#11)
Browse files Browse the repository at this point in the history
  • Loading branch information
moattarwork authored Jul 30, 2024
1 parent 17290ef commit bc3a429
Show file tree
Hide file tree
Showing 20 changed files with 89 additions and 92 deletions.
2 changes: 1 addition & 1 deletion GitVersion.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
next-version: 2.1.0
next-version: 2.2.0
mode: Mainline
major-version-bump-message: '\+semver:\s?(breaking|major)'
minor-version-bump-message: '\+semver:\s?(feature|minor)'
Expand Down
19 changes: 7 additions & 12 deletions src/LittleBlocks.AspNetCore.Bootstrap/ApiPipelineOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,14 @@

namespace LittleBlocks.AspNetCore.Bootstrap;

public sealed class ApiPipelineOptions
public sealed class ApiPipelineOptions(
IConfiguration configuration,
IHostEnvironment environment,
ILoggerFactory loggerFactory)
{
public ApiPipelineOptions(IConfiguration configuration, IHostEnvironment environment,
ILoggerFactory loggerFactory)
{
Configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
Environment = environment ?? throw new ArgumentNullException(nameof(environment));
LoggerFactory = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
}

public IConfiguration Configuration { get; }
public IHostEnvironment Environment { get; }
public ILoggerFactory LoggerFactory { get; }
public IConfiguration Configuration { get; } = configuration ?? throw new ArgumentNullException(nameof(configuration));
public IHostEnvironment Environment { get; } = environment ?? throw new ArgumentNullException(nameof(environment));
public ILoggerFactory LoggerFactory { get; } = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
public Action PostAuthenticationConfigure { get; } = null;
public Action<IEndpointRouteBuilder> PreEndPointsConfigure { get; } = null;
public Action<IEndpointRouteBuilder> PostEndPointsConfigure { get; } = null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,28 +14,38 @@
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

using Serilog;

namespace LittleBlocks.AspNetCore.Bootstrap;

public static class ApplicationBuilderExtensions
{
public static void UseDefaultApiPipeline(this IApplicationBuilder app,
IConfiguration configuration,
IWebHostEnvironment env,
IHostApplicationLifetime lifetime,
ILoggerFactory loggerFactory)
{
if (app == null) throw new ArgumentNullException(nameof(app));
if (configuration == null) throw new ArgumentNullException(nameof(configuration));
if (env == null) throw new ArgumentNullException(nameof(env));
if (loggerFactory == null) throw new ArgumentNullException(nameof(loggerFactory));
ArgumentNullException.ThrowIfNull(lifetime);
ArgumentNullException.ThrowIfNull(app);
ArgumentNullException.ThrowIfNull(configuration);
ArgumentNullException.ThrowIfNull(env);
ArgumentNullException.ThrowIfNull(loggerFactory);

InitiateFlushOutstandingOperations(lifetime);
var options = new ApiPipelineOptions(configuration, env, loggerFactory);
app.UseDefaultApiPipeline(options);
}

public static void UseDefaultApiPipeline(this IApplicationBuilder app, ApiPipelineOptions options)
private static void InitiateFlushOutstandingOperations(IHostApplicationLifetime lifetime)
{
lifetime.ApplicationStopped.Register(Log.CloseAndFlush);
}

private static void UseDefaultApiPipeline(this IApplicationBuilder app, ApiPipelineOptions options)
{
if (app == null) throw new ArgumentNullException(nameof(app));
if (options == null) throw new ArgumentNullException(nameof(options));
ArgumentNullException.ThrowIfNull(app);
ArgumentNullException.ThrowIfNull(options);

var appInfo = options.Configuration.GetApplicationInfo();
var authOptions = options.Configuration.GetAuthOptions();
Expand Down Expand Up @@ -87,8 +97,8 @@ public static void UseDefaultApiPipeline(this IApplicationBuilder app, ApiPipeli

public static void UseStartPage(this IEndpointRouteBuilder endpoints, string applicationName)
{
if (endpoints == null) throw new ArgumentNullException(nameof(endpoints));
if (applicationName == null) throw new ArgumentNullException(nameof(applicationName));
ArgumentNullException.ThrowIfNull(endpoints);
ArgumentNullException.ThrowIfNull(applicationName);

endpoints.MapGet("/", context =>
{
Expand Down Expand Up @@ -128,6 +138,6 @@ private static string LoadStartPageFromEmbeddedResource(string applicationName)
private static void LogResolvedEnvironment(IHostEnvironment env, ILoggerFactory loggerFactory)
{
var log = loggerFactory.CreateLogger("Startup");
log.LogInformation($"Application is started in '{env.EnvironmentName.ToUpper()}' environment ...");
log.LogInformation($"{nameof(Application)} is started in '{env.EnvironmentName.ToUpper()}' environment ...");
}
}
2 changes: 1 addition & 1 deletion src/LittleBlocks.AspNetCore/HostAsWeb.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ private static IWebHost Build<TStartup>(
})
.ConfigureServices((context, services) =>
{
loggerConfigure(new LoggerBuilder(context.HostingEnvironment, context.Configuration, new LoggerConfiguration())).Build<TStartup>();
loggerConfigure(new LoggerBuilder(services, context.HostingEnvironment, context.Configuration)).Build<TStartup>();
})
.Build();

Expand Down
25 changes: 11 additions & 14 deletions src/LittleBlocks.AspNetCore/Logging/SeriLog/Fluent/LoggerBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@

namespace LittleBlocks.AspNetCore.Logging.SeriLog.Fluent;

public sealed class LoggerBuilder : ILoggerBuilder, IBuildLogger
public sealed class LoggerBuilder(
IServiceCollection services,
IHostEnvironment environment,
IConfiguration configuration)
: ILoggerBuilder, IBuildLogger
{
private const string LogMessageTemplate =
"{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{MachineName}] [{EnvironmentUserName}] [{ProcessId}] " +
Expand All @@ -25,25 +29,18 @@ public sealed class LoggerBuilder : ILoggerBuilder, IBuildLogger
private const string SerilogConfigSectionName = "Logging:Serilog";
private const string SerilogMinimumLevelKey = "MinimumLevel";
private const LogEventLevel DefaultLogLevel = LogEventLevel.Information;
private readonly IHostEnvironment _environment;
private readonly IConfiguration _configuration;
private readonly LoggerConfiguration _loggerConfiguration;

private readonly IServiceCollection _services = services ?? throw new ArgumentNullException(nameof(services));
private readonly IHostEnvironment _environment = environment ?? throw new ArgumentNullException(nameof(environment));
private readonly IConfiguration _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));

private Func<ISetFileSizeLimit, IBuildSeriLogOptions> _optionsProvider;
private Func<ISinkBuilderContext, ISinkBuilderContext> _sinksProvider;

public LoggerBuilder(IHostEnvironment environment, IConfiguration configuration, LoggerConfiguration loggerConfiguration)
{
_environment = environment ?? throw new ArgumentNullException(nameof(environment));
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
_loggerConfiguration = loggerConfiguration ?? throw new ArgumentNullException(nameof(loggerConfiguration));
}

public void Build<TStartup>() where TStartup : class
{
ConfigureLogger<TStartup>(_loggerConfiguration, _optionsProvider, _sinksProvider);
_services.AddSerilog(lg => ConfigureLogger<TStartup>(lg, _optionsProvider, _sinksProvider));
}

public IConfiguration Configuration => _configuration;
public IHostEnvironment Environment => _environment;

Expand Down Expand Up @@ -86,7 +83,7 @@ private void ConfigureLogger<TStartup>(LoggerConfiguration loggerConfiguration,
Func<ISetFileSizeLimit, IBuildSeriLogOptions> optionsProvider,
Func<ISinkBuilderContext, ISinkBuilderContext> sinksProvider) where TStartup : class
{
if (loggerConfiguration == null) throw new ArgumentNullException(nameof(loggerConfiguration));
ArgumentNullException.ThrowIfNull(loggerConfiguration);

var env = _environment;
var configuration = _configuration;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,12 @@ private HttpContext CorrelateRequest(HttpContext context)
new List<string> {HttpHeaders.HttpCorrelationId, HttpHeaders.HttpRequestId});

correlationId = _correlationIdProvider.GenerateId();
context.Request.Headers.Add(HttpHeaders.HttpRequestId, correlationId);
context.Request.Headers.Append(HttpHeaders.HttpRequestId, correlationId);
}

context.Response.OnStarting(state =>
{
((HttpContext) state).Response.Headers.Add(HttpHeaders.HttpRequestId, correlationId);
((HttpContext) state).Response.Headers.Append(HttpHeaders.HttpRequestId, correlationId);
return Task.FromResult(0);
}, context);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ namespace LittleBlocks.AspNetCore.Security.Impersonation;
public sealed class ImpersonationAuthenticationHandler : AuthenticationHandler<ImpersonationBearerOptions>
{
public ImpersonationAuthenticationHandler(IOptionsMonitor<ImpersonationBearerOptions> options,
ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock): base(options, logger, encoder, clock)

Check warning on line 26 in src/LittleBlocks.AspNetCore/Security/Impersonation/ImpersonationAuthenticationHandler.cs

View workflow job for this annotation

GitHub Actions / build

'ISystemClock' is obsolete: 'Use TimeProvider instead.'

Check warning on line 26 in src/LittleBlocks.AspNetCore/Security/Impersonation/ImpersonationAuthenticationHandler.cs

View workflow job for this annotation

GitHub Actions / build

'AuthenticationHandler<ImpersonationBearerOptions>.AuthenticationHandler(IOptionsMonitor<ImpersonationBearerOptions>, ILoggerFactory, UrlEncoder, ISystemClock)' is obsolete: 'ISystemClock is obsolete, use TimeProvider on AuthenticationSchemeOptions instead.'

Check warning on line 26 in src/LittleBlocks.AspNetCore/Security/Impersonation/ImpersonationAuthenticationHandler.cs

View workflow job for this annotation

GitHub Actions / build

'ISystemClock' is obsolete: 'Use TimeProvider instead.'

Check warning on line 26 in src/LittleBlocks.AspNetCore/Security/Impersonation/ImpersonationAuthenticationHandler.cs

View workflow job for this annotation

GitHub Actions / build

'AuthenticationHandler<ImpersonationBearerOptions>.AuthenticationHandler(IOptionsMonitor<ImpersonationBearerOptions>, ILoggerFactory, UrlEncoder, ISystemClock)' is obsolete: 'ISystemClock is obsolete, use TimeProvider on AuthenticationSchemeOptions instead.'
{
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,9 @@ private static IHost Build<TStartup>(
config.ConfigureBuilder(options);
configurationConfigure(config);
})
.UseSerilog((context, configuration) =>
.ConfigureServices((context, services) =>
{
loggerConfigure(new LoggerBuilder(context.HostingEnvironment, context.Configuration,
configuration)).Build<TStartup>();
loggerConfigure(new LoggerBuilder(services, context.HostingEnvironment, context.Configuration)).Build<TStartup>();
})
.Build();

Expand Down
4 changes: 2 additions & 2 deletions src/LittleBlocks.Logging.SeriLog/SinkBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ public static class SinkBuilderExtensions
{
public static ISinkBuilderContext BuildAndCloneContext(this ISinkBuilder builder, ISinkBuilderContext sinkBuilderContext)
{
if (builder == null) throw new ArgumentNullException(nameof(builder));
if (sinkBuilderContext == null) throw new ArgumentNullException(nameof(sinkBuilderContext));
ArgumentNullException.ThrowIfNull(builder);
ArgumentNullException.ThrowIfNull(sinkBuilderContext);

var loggerConfiguration = builder.Build();
return sinkBuilderContext.Clone(loggerConfiguration);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public async Task Given_CorrelationId_IsPresent_ThenInvokeNextMiddlewareComponen
var next = Substitute.For<RequestDelegate>();
var sut = new CorrelateRequestMiddleware(next, options, idProvider);
var context = GetDefaultHttpContext();
context.Request.Headers.Add(header, Guid.NewGuid().ToString());
context.Request.Headers.Append(header, Guid.NewGuid().ToString());

// Act
await sut.Invoke(context);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public sealed class HealthControllerTests
public async Task GivenAPIRunning_WhenHealthRequested_ShouldReturnHealthy()
{
// Arrange
using var fixture = TestApplicationFactory<StartupForHealthy>.Create();
await using var fixture = TestApplicationFactory<StartupForHealthy>.Create();

// Act
var response = await fixture.CreateClient().GetAsync($"health");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

using Microsoft.Extensions.Hosting;

namespace LittleBlocks.Sample.WebAPI.IntegrationTests.Helpers;

public abstract class StartupForAuthentication<T> where T : class
Expand Down Expand Up @@ -45,8 +47,8 @@ public void ConfigureServices(IServiceCollection services)
);
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime, ILoggerFactory loggerFactory)
{
app.UseDefaultApiPipeline(Configuration, env, loggerFactory);
app.UseDefaultApiPipeline(Configuration, env, lifetime, loggerFactory);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,13 @@
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

using Microsoft.Extensions.Hosting;

namespace LittleBlocks.Sample.WebAPI.IntegrationTests.Helpers;

public class StartupForAutomapper
public class StartupForAutomapper(IConfiguration configuration)
{
public StartupForAutomapper(IConfiguration configuration)
{
Configuration = configuration;
}

private IConfiguration Configuration { get; }
private IConfiguration Configuration { get; } = configuration;

public void ConfigureServices(IServiceCollection services)
{
Expand All @@ -44,8 +41,8 @@ public void ConfigureServices(IServiceCollection services)
);
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime, ILoggerFactory loggerFactory)
{
app.UseDefaultApiPipeline(Configuration, env, loggerFactory);
app.UseDefaultApiPipeline(Configuration, env, lifetime, loggerFactory);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,13 @@
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

using Microsoft.Extensions.Hosting;

namespace LittleBlocks.Sample.WebAPI.IntegrationTests.Helpers;

public class StartupForConfiguration
public class StartupForConfiguration(IConfiguration configuration)
{
public StartupForConfiguration(IConfiguration configuration)
{
Configuration = configuration;
}

private IConfiguration Configuration { get; }
private IConfiguration Configuration { get; } = configuration;

public void ConfigureServices(IServiceCollection services)
{
Expand All @@ -35,8 +32,8 @@ public void ConfigureServices(IServiceCollection services)
);
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime, ILoggerFactory loggerFactory)
{
app.UseDefaultApiPipeline(Configuration, env, loggerFactory);
app.UseDefaultApiPipeline(Configuration, env, lifetime, loggerFactory);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>.

using System.Net.Http;
using Microsoft.Extensions.Hosting;

namespace LittleBlocks.Sample.WebAPI.IntegrationTests.Helpers;

Expand Down Expand Up @@ -46,10 +47,10 @@ public void ConfigureServices(IServiceCollection services)
})
);
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime, ILoggerFactory loggerFactory)
{
app.UseDefaultApiPipeline(Configuration, env, loggerFactory);
app.UseDefaultApiPipeline(Configuration, env, lifetime, loggerFactory);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

using Microsoft.Extensions.Hosting;

namespace LittleBlocks.Sample.WebAPI.IntegrationTests.Helpers;

public class StartupForIntegration
Expand Down Expand Up @@ -42,9 +44,8 @@ public void ConfigureServices(IServiceCollection services)
})
);
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime, ILoggerFactory loggerFactory)
{
app.UseDefaultApiPipeline(Configuration, env, loggerFactory);
app.UseDefaultApiPipeline(Configuration, env, lifetime, loggerFactory);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

using Microsoft.Extensions.Hosting;

namespace LittleBlocks.Sample.WebAPI.IntegrationTests.Helpers;

public class StartupForValues
Expand Down Expand Up @@ -43,8 +45,8 @@ public void ConfigureServices(IServiceCollection services)
);
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime, ILoggerFactory loggerFactory)
{
app.UseDefaultApiPipeline(Configuration, env, loggerFactory);
app.UseDefaultApiPipeline(Configuration, env, lifetime, loggerFactory);
}
}
Loading

0 comments on commit bc3a429

Please sign in to comment.