Adds Serilog structured logging

This commit is contained in:
BinaryAlley committed 2024-11-06 12:04:03 +02:00
1 parent 98b8d1aba5
commit 21db396bf3
9 files changed
+249 -24

No files matched your search

+2 -1
View File
@@ -31,7 +31,8 @@ bld/
*.sln.iml
# Common
*.Development.json
*.[Dd]evelopment.json
*.[Tt]est.json
# Windows image file caches
Thumbs.db
@@ -3,13 +3,13 @@
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<BaseOutputPath>$(SolutionDir)..\bin\server\</BaseOutputPath>
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<UserSecretsId>37d55c87-4374-4971-82e9-012fcaad1853</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<ContainerRepository>lumina-server</ContainerRepository>
<DockerfileTag>lumina-server</DockerfileTag>
<ContainerRepository>lumina-api</ContainerRepository>
<DockerfileTag>lumina-api</DockerfileTag>
<DockerComposeProjectPath>..\docker-compose.dcproj</DockerComposeProjectPath>
</PropertyGroup>
@@ -30,6 +30,11 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Serilog" Version="4.1.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
<PackageReference Include="Serilog.Enrichers.AspnetcoreHttpcontext" Version="1.1.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
</ItemGroup>
<ItemGroup>
+39
View File
@@ -3,12 +3,16 @@ using FastEndpoints;
using FastEndpoints.Swagger;
using Lumina.Application.Common.DependencyInjection;
using Lumina.DataAccess.Common.DependencyInjection;
using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.DependencyInjection;
using Lumina.Infrastructure.Common.DependencyInjection;
using Lumina.Presentation.Api.Common.DependencyInjection;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Serilog;
using System;
using System.IO;
using System.Threading.Tasks;
@@ -38,7 +42,42 @@ public class Program
builder.Services.AddDataAccessLayerServices();
builder.Services.AddDomainLayerServices();
// determine log path based on environment
string logPath;
if (Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER") == "true")
logPath = Environment.GetEnvironmentVariable("LOG_PATH") ?? "/logs"; // use docker volume path
else
logPath = Path.Combine(AppContext.BaseDirectory, "logs"); // use local binary path
Directory.CreateDirectory(logPath);
// set environment variable for Serilog configuration
Environment.SetEnvironmentVariable("LOG_PATH", logPath);
builder.Host.UseSerilog((context, services, configuration) =>
{
configuration.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext();
});
WebApplication app = builder.Build();
app.UseSerilogRequestLogging();
// apply any pending migrations
using (IServiceScope scope = app.Services.CreateScope())
{
IServiceProvider services = scope.ServiceProvider;
try
{
LuminaDbContext context = services.GetRequiredService<LuminaDbContext>();
await context.Database.MigrateAsync();
}
catch (Exception ex)
{
ILogger logger = services.GetRequiredService<ILogger>();
logger.Fatal(ex, "Failed to run database migrations");
}
}
app.UseCors("AllowAll");
+31 -7
View File
@@ -1,21 +1,45 @@
{
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning",
"Microsoft.AspNetCore": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"WriteTo": [
{
"Name": "Debug"
},
{
"Name": "Console"
"Name": "Console",
"Args": {
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Literate, Serilog.Sinks.Console",
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
}
},
{
"Name": "File",
"Args": {
"path": "Logs/lumina_api_.log",
"path": "${LOG_PATH}/lumina_api_.log",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
"retainedFileCountLimit": 7,
"fileSizeLimitBytes": 10485760,
"rollOnFileSizeLimit": true,
"shared": true,
"flushToDiskInterval": "00:00:01"
}
}
]
],
"Enrich": [
"FromLogContext",
"WithMachineName",
"WithThreadId",
"WithEnvironmentName"
],
"Properties": {
"Application": "LuminaApi"
}
},
"AllowedHosts": "*"
}
@@ -1,8 +1,14 @@
#region ========================================================================= USING =====================================================================================
using FluentValidation;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Authorization;
using Lumina.Presentation.Web.Common.Exceptions;
using Lumina.Presentation.Web.Common.Filters;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.DependencyInjection;
using Polly;
using Polly.CircuitBreaker;
@@ -12,6 +18,7 @@ using System;
using System.Net;
using System.Net.Http;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Common.DependencyInjection;
@@ -36,6 +43,66 @@ public static class PresentationWebLayerServices
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
// configure cookie-based authentication
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
// basic path configuration
options.LoginPath = "/account/login";
options.LogoutPath = "/account/logout";
options.AccessDeniedPath = "/account/access-denied";
// Cookie configuration
options.Cookie = new CookieBuilder
{
Name = ".Lumina.Auth", // unique name to avoid conflicts
HttpOnly = true, // prevent JavaScript access
SameSite = SameSiteMode.Lax, // balance between security and functionality
SecurePolicy = CookieSecurePolicy.Always, // require HTTPS
Path = "/", // make cookie available for all paths
IsEssential = true // mark as essential for GDPR
};
// security settings
options.ExpireTimeSpan = TimeSpan.FromHours(24); // TODO: perhaps make it configurable by user?
options.SlidingExpiration = true;
// handle validation to support various deployment scenarios
options.Events = new CookieAuthenticationEvents
{
// handle redirects to work with different base paths
OnRedirectToLogin = context =>
{
// preserve any base path or subdirectory
string redirectPath = context.RedirectUri;
if (context.Request.PathBase.HasValue)
redirectPath = context.Request.PathBase + options.LoginPath + new QueryString("?returnUrl=") + Uri.EscapeDataString(context.Request.PathBase + context.Request.Path);
context.Response.Redirect(redirectPath);
return Task.CompletedTask;
}
};
});
// add an authorization policy that ensures application is initialized with super admin account before allowing access
services.AddAuthorizationBuilder()
.AddPolicy("RequireInitialization", policy => policy.Requirements.Add(new InitializationRequirement()));
// add forwarded headers middleware to handle reverse proxy scenarios
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;
options.KnownNetworks.Clear();
options.KnownProxies.Clear();
});
// configure session management to maintain user-specific data across requests
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(30); // session expires after 30 minutes of inactivity
options.Cookie.HttpOnly = true; // prevent JavaScript access to session cookie, for security
options.Cookie.IsEssential = true; // mark session cookie as essential, for GDPR compliance
});
// scan the current assembly for validators and register them to the DI container
services.AddValidatorsFromAssemblyContaining<Program>(ServiceLifetime.Singleton);
@@ -56,12 +123,16 @@ public static class PresentationWebLayerServices
AsyncPolicyWrap<HttpResponseMessage> policy = Policy.WrapAsync(retryPolicy, circuitBreakerPolicy);
// register the typed client used for the API interaction
// register the HTTP typed client used for the API interaction
services.AddHttpClient<IApiHttpClient, ApiHttpClient>()
.AddPolicyHandler(retryPolicy)
.AddPolicyHandler(circuitBreakerPolicy);
// enable access to the current HTTP context in non-controller classes
services.AddHttpContextAccessor();
services.AddScoped<ApiExceptionFilter>();
services.AddScoped<IAuthorizationHandler, InitializationHandler>();
return services;
}
@@ -1,14 +1,17 @@
using Lumina.Presentation.Web.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Serilog;
using System.Diagnostics;
namespace Lumina.Presentation.Web.Controllers;
[Authorize]
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly ILogger _logger;
public HomeController(ILogger<HomeController> logger)
public HomeController(ILogger logger)
{
_logger = logger;
}
@@ -3,9 +3,14 @@
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>disable</ImplicitUsings>
<BaseOutputPath>$(SolutionDir)..\bin\client\</BaseOutputPath>
<BaseOutputPath>$(SolutionDir)..\bin\web\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<UserSecretsId>6413036f-92d7-45d8-a8B1-205200089047</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<ContainerRepository>lumina-web</ContainerRepository>
<DockerfileTag>lumina-web</DockerfileTag>
<DockerComposeProjectPath>..\docker-compose.dcproj</DockerComposeProjectPath>
</PropertyGroup>
<ItemGroup>
@@ -18,11 +23,18 @@
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="8.0.8" />
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.0" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.0" />
<PackageReference Include="Polly" Version="8.4.1" />
<PackageReference Include="Serilog" Version="4.1.0" />
<PackageReference Include="Serilog.AspNetCore" Version="8.0.3" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
</ItemGroup>
<!--disable warnings generated by Mediator source generator-->
<PropertyGroup>
<NoWarn>$(NoWarn);TS6385</NoWarn>
<UserSecretsId>10a94da9-18ed-4c70-a9da-b461e08958c4</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>
</Project>
+36 -5
View File
@@ -3,6 +3,10 @@ using Lumina.Presentation.Web.Common.DependencyInjection;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Primitives;
using Serilog;
using System;
using System.IO;
using System.Threading.Tasks;
#endregion
@@ -24,8 +28,27 @@ public class Program
builder.Services.BindConfiguration(builder.Configuration);
builder.Services.AddPresentationWebLayerServices();
// determine log path based on environment
string logPath;
if (Environment.GetEnvironmentVariable("DOTNET_RUNNING_IN_CONTAINER") == "true")
logPath = Environment.GetEnvironmentVariable("LOG_PATH") ?? "/logs"; // use docker volume path
else
logPath = Path.Combine(AppContext.BaseDirectory, "logs"); // use local binary path
Directory.CreateDirectory(logPath);
// set environment variable for Serilog configuration
Environment.SetEnvironmentVariable("LOG_PATH", logPath);
builder.Host.UseSerilog((context, services, configuration) =>
{
configuration.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext();
});
WebApplication app = builder.Build();
app.UseSerilogRequestLogging();
// configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
@@ -36,14 +59,22 @@ public class Program
//app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();
app.UseForwardedHeaders();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
// handle path base from reverse proxies
app.Use((context, next) =>
{
if (context.Request.Headers.TryGetValue("X-Forwarded-Prefix", out StringValues pathBase))
context.Request.PathBase = pathBase.ToString();
return next();
});
app.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
await app.RunAsync();
}
+42 -3
View File
@@ -1,8 +1,47 @@
{
"Logging": {
"LogLevel": {
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
"Override": {
"Microsoft": "Warning",
"System": "Warning",
"Microsoft.AspNetCore": "Warning",
"Microsoft.Hosting.Lifetime": "Information",
"Microsoft.AspNetCore.Mvc.Razor": "Error",
"Microsoft.AspNetCore.Mvc.RazorPages": "Error"
}
},
"WriteTo": [
{
"Name": "Console",
"Args": {
"theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Literate, Serilog.Sinks.Console",
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
}
},
{
"Name": "File",
"Args": {
"path": "${LOG_PATH}/lumina_web_.log",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}",
"retainedFileCountLimit": 7,
"fileSizeLimitBytes": 10485760,
"rollOnFileSizeLimit": true,
"shared": true,
"flushToDiskInterval": "00:00:01"
}
}
],
"Enrich": [
"FromLogContext",
"WithMachineName",
"WithThreadId",
"WithEnvironmentName",
"WithRequestId"
],
"Properties": {
"Application": "LuminaWeb"
}
},
"AllowedHosts": "*",