Switch logging framework from NLog to Serilog

Replaced NLog with Serilog for improved logging capabilities.
Updated `EnvelopeGenerator.Server.csproj` to include Serilog
dependencies and removed NLog-related packages. Configured
Serilog with console, file, and SQLite sinks, and integrated
Serilog UI for log viewing.

Modified `Program.cs` to initialize Serilog, added middleware
for request logging and UI, and replaced NLog exception
handling with Serilog's `Log.Fatal`. Updated `appsettings.json`
and `appsettings.Development.json` to include Serilog
configuration and removed NLog-specific settings.

Performed code cleanup by removing unused NLog directives
and adding Serilog-related imports.
This commit is contained in:
2026-11-25 13:47:16 +01:00
parent b096cb0e00
commit dfeb56aa9c
4 changed files with 98 additions and 59 deletions

View File

@@ -46,8 +46,13 @@
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.17" />
<PackageReference Include="Microsoft.Identity.Client" Version="4.82.1" />
<PackageReference Include="NLog" Version="5.2.5" />
<PackageReference Include="NLog.Web.AspNetCore" Version="5.3.0" />
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="10.0.1" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
<PackageReference Include="Serilog.Sinks.SQLite" Version="7.0.0" />
<PackageReference Include="Serilog.UI" Version="3.2.0" />
<PackageReference Include="Serilog.UI.SqliteProvider" Version="1.1.0" />
<PackageReference Include="PDFsharp" Version="6.2.4" />
<PackageReference Include="Scalar.AspNetCore" Version="2.2.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="8.1.1" />

View File

@@ -26,30 +26,64 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using NLog;
using NLog.Web;
using Serilog;
using Serilog.Ui.Core.Extensions;
using Serilog.Ui.SqliteDataProvider.Extensions;
using Serilog.Ui.Web.Extensions;
using Scalar.AspNetCore;
using System.Globalization;
using MudBlazor.Services;
var logger = LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger();
logger.Info("EnvelopeGenerator.Server logging initialized!");
var tempConfig = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
.AddJsonFile("appsettings.Secrets.json", optional: true, reloadOnChange: false)
.Build();
var logDirectoryRaw = tempConfig.GetValue<string>("Application:LogDirectory") ?? "logs";
var logDirectory = Path.IsPathRooted(logDirectoryRaw)
? logDirectoryRaw
: Path.Combine(AppContext.BaseDirectory, logDirectoryRaw);
Directory.CreateDirectory(logDirectory);
var sqliteDbPath = Path.Combine(logDirectory, "logs.db");
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.MinimumLevel.Override("Microsoft", Serilog.Events.LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.AspNetCore", Serilog.Events.LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.EntityFrameworkCore", Serilog.Events.LogEventLevel.Warning)
.MinimumLevel.Override("System", Serilog.Events.LogEventLevel.Warning)
.Enrich.FromLogContext()
.WriteTo.Console(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
.WriteTo.File(
path: Path.Combine(logDirectory, "EnvelopeGenerator.Server-.log"),
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 30,
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
.WriteTo.SQLite(sqliteDbPath, storeTimestampInUtc: true)
.CreateBootstrapLogger();
try
{
Log.Information("Starting EnvelopeGenerator.Server");
var builder = WebApplication.CreateBuilder(args);
// Load YARP configuration from yarp.json
builder.Configuration.AddJsonFile("yarp.json", optional: true, reloadOnChange: true);
builder.Configuration.AddJsonFile("appsettings.Secrets.json", optional: true, reloadOnChange: true);
builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
if (!builder.Environment.IsDevelopment())
{
builder.Logging.ClearProviders();
builder.Host.UseNLog();
}
builder.Host.UseSerilog((context, services, configuration) => configuration
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext()
.WriteTo.Console(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
.WriteTo.File(
path: Path.Combine(logDirectory, "EnvelopeGenerator.Server-.log"),
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 30,
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
.WriteTo.SQLite(sqliteDbPath, storeTimestampInUtc: true));
var config = builder.Configuration;
@@ -164,6 +198,15 @@ try
}
});
builder.Services.AddSerilogUi(options =>
{
options.UseSqliteServer(dbOpt =>
{
dbOpt.WithConnectionString($"Data Source={sqliteDbPath}");
dbOpt.WithTable("Logs");
});
});
// Database Context
var useDbMigration = Environment.GetEnvironmentVariable("MIGRATION_TEST_MODE") == true.ToString() || config.GetValue<bool>("UseDbMigration");
var cnnStrName = useDbMigration ? "DbMigrationTest" : "Default";
@@ -403,6 +446,8 @@ try
// Exception handling middleware for API controllers
app.UseMiddleware<EnvelopeGenerator.Server.Middleware.ExceptionHandlingMiddleware>();
app.UseSerilogRequestLogging();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
@@ -431,6 +476,8 @@ try
app.MapScalarApiReference();
}
app.UseSerilogUi();
// Set CORS policy
app.UseCors("AllowSpecificOriginsPolicy");
@@ -473,10 +520,16 @@ try
.AddInteractiveWebAssemblyRenderMode()
.AddAdditionalAssemblies(typeof(EnvelopeGenerator.Server.Client._Imports).Assembly);
Log.Information("EnvelopeGenerator.Server started successfully");
app.Run();
}
catch (Exception ex)
{
logger.Error(ex, "Stopped program because of exception");
Log.Fatal(ex, "EnvelopeGenerator.Server failed to start");
throw;
}
finally
{
Log.CloseAndFlush();
}

View File

@@ -4,8 +4,18 @@
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"Serilog": {
"MinimumLevel": {
"Default": "Debug",
"Override": {
"Microsoft": "Warning",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore": "Warning",
"System": "Warning"
}
,
}
},
"AuthClientParams": {
"Url": "http://172.24.12.39:9090/auth-hub",
"PublicKeys": [

View File

@@ -12,6 +12,20 @@
"Microsoft.AspNetCore": "Warning"
}
},
"Application": {
"LogDirectory": "E:\\LogFiles\\Digital Data\\signFlow"
},
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore": "Warning",
"System": "Warning"
}
}
},
"AllowedHosts": "*",
"AllowedOrigins": [
"http://localhost:4200",
@@ -80,49 +94,6 @@
"media-src 'self'",
"object-src 'self'"
],
"NLog": {
"throwConfigExceptions": true,
"variables": {
"logDirectory": "E:\\LogFiles\\Digital Data\\signFlow",
"logFileNamePrefix": "${shortdate}-ECM.EnvelopeGenerator.Server"
},
"targets": {
"infoLogs": {
"type": "File",
"fileName": "${logDirectory}\\${logFileNamePrefix}-Info.log",
"maxArchiveDays": 30
},
"errorLogs": {
"type": "File",
"fileName": "${logDirectory}\\${logFileNamePrefix}-Error.log",
"maxArchiveDays": 30
},
"criticalLogs": {
"type": "File",
"fileName": "${logDirectory}\\${logFileNamePrefix}-Critical.log",
"maxArchiveDays": 30
}
},
// Trace, Debug, Info, Warn, Error and *Fatal*
"rules": [
{
"logger": "*",
"minLevel": "Info",
"maxLevel": "Warn",
"writeTo": "infoLogs"
},
{
"logger": "*",
"level": "Error",
"writeTo": "errorLogs"
},
{
"logger": "*",
"level": "Fatal",
"writeTo": "criticalLogs"
}
]
},
"ContactLink": {
"Label": "Kontakt",
"Href": "https://digitaldata.works/",