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

@@ -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();
}