refactor: migrate logging infrastructure from NLog to Serilog

- Replace NLog packages with Serilog.AspNetCore and related dependencies
- Add Serilog.UI with SQLite provider for log visualization
- Implement environment-based logging configuration:
  * Development: Console output with simplified template
  * Production: File-based logging with separate files per level
- Add SQLite sink for persistent log storage and web UI access
- Configure rolling file policies with configurable retention
- Update appsettings.Logging.json to use Serilog configuration format
- Enable Serilog self-diagnostics for troubleshooting
This commit is contained in:
2026-08-03 17:11:13 +02:00
parent cb12cfcbc2
commit 003f4c60f6
3 changed files with 109 additions and 65 deletions

View File

@@ -1,27 +1,96 @@
using Microsoft.AspNetCore.Rewrite; using Microsoft.AspNetCore.Rewrite;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using NLog;
using NLog.Web;
using ReC.API.Middleware; using ReC.API.Middleware;
using ReC.Application; using ReC.Application;
using ReC.Infrastructure; using ReC.Infrastructure;
using Serilog;
using Serilog.Ui.Core.Extensions;
using Serilog.Ui.SqliteDataProvider.Extensions;
using Serilog.Ui.Web.Extensions;
using System.Reflection; using System.Reflection;
using LogLevel = Microsoft.Extensions.Logging.LogLevel; using LogLevel = Microsoft.Extensions.Logging.LogLevel;
var logger = LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger(); // Enable Serilog self-diagnostics
logger.Info("Logging initialized!"); Serilog.Debugging.SelfLog.Enable(msg => Console.WriteLine($"[SERILOG] {msg}"));
// Build temporary configuration to read log directory from appsettings.Logging.json
var tempConfig = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false)
.AddJsonFile("appsettings.Logging.json", optional: false)
.AddEnvironmentVariables()
.Build();
var isDevelopment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development";
var logDirectory = tempConfig.GetValue<string>("Serilog:LogDirectory")
?? Path.Combine(AppContext.BaseDirectory, "logs");
var retainedFileCountLimit = tempConfig.GetValue("Serilog:RetainedFileCountLimit", 30);
Directory.CreateDirectory(logDirectory);
var sqliteDbPath = Path.Combine(logDirectory, "logs.db");
var logFilePathTemplate = Path.Combine(logDirectory, ".Rec.API-.log");
Console.WriteLine($"[INFO] Log Directory: {logDirectory}");
// Configure Serilog based on environment:
// Development : Console + SQLite (+ Web UI)
// Production : File (per-level) + SQLite (+ Web UI)
var loggerConfig = new LoggerConfiguration()
.MinimumLevel.Information()
.MinimumLevel.Override("Microsoft.AspNetCore", Serilog.Events.LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.EntityFrameworkCore", Serilog.Events.LogEventLevel.Warning)
.Enrich.FromLogContext();
if (isDevelopment)
{
loggerConfig.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}");
}
else
{
loggerConfig
.WriteTo.File(
Path.Combine(logDirectory, ".Rec.API-Info.log"),
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: retainedFileCountLimit,
restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Information,
outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
.WriteTo.File(
Path.Combine(logDirectory, ".Rec.API-Warning.log"),
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: retainedFileCountLimit,
restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Warning,
outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
.WriteTo.File(
Path.Combine(logDirectory, ".Rec.API-Error.log"),
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: retainedFileCountLimit,
restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Error,
outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
.WriteTo.File(
Path.Combine(logDirectory, ".Rec.API-Critical.log"),
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: retainedFileCountLimit,
restrictedToMinimumLevel: Serilog.Events.LogEventLevel.Fatal,
outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}");
}
// SQLite sink is always active (used by Serilog Web UI)
loggerConfig.WriteTo.SQLite(sqliteDbPath, storeTimestampInUtc: true);
Log.Logger = loggerConfig.CreateLogger();
Log.Information("Logging initialized!");
try try
{ {
Log.Information("Starting ReC.API application");
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
builder.Logging.SetMinimumLevel(LogLevel.Trace); // Use Serilog for logging
builder.Host.UseSerilog();
if (!builder.Environment.IsDevelopment())
{
builder.Logging.ClearProviders();
builder.Host.UseNLog();
}
var config = builder.Configuration; var config = builder.Configuration;
@@ -71,6 +140,16 @@ try
c.IncludeXmlComments(xmlPath); c.IncludeXmlComments(xmlPath);
}); });
// Serilog Web UI — SQLite provider, same path used by the SQLite sink above
builder.Services.AddSerilogUi(logUIOpt =>
{
logUIOpt.UseSqliteServer(dbOpt =>
{
dbOpt.WithConnectionString($"Data Source={sqliteDbPath}");
dbOpt.WithTable("Logs");
});
});
var app = builder.Build(); var app = builder.Build();
app.UseMiddleware<ExceptionHandlingMiddleware>(); app.UseMiddleware<ExceptionHandlingMiddleware>();
@@ -89,14 +168,21 @@ try
app.UseAuthorization(); app.UseAuthorization();
// Serilog Web UI is always active (both Development and Production)
app.UseSerilogUi();
app.MapControllers(); app.MapControllers();
app.Run(); app.Run();
} }
catch(Exception ex) catch (Exception ex)
{ {
logger.Error(ex, "Stopped program because of exception"); Log.Fatal(ex, "Stopped program because of exception");
throw; throw;
} }
finally
{
Log.CloseAndFlush();
}
public partial class Program; public partial class Program;

View File

@@ -23,8 +23,13 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="9.0.11" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="9.0.11" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" /> <PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
<PackageReference Include="NLog" Version="5.2.5" /> <PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
<PackageReference Include="NLog.Web.AspNetCore" Version="5.3.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" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@@ -5,55 +5,8 @@
"Microsoft.AspNetCore": "Warning" "Microsoft.AspNetCore": "Warning"
} }
}, },
"NLog": { "Serilog": {
"throwConfigExceptions": true, "LogDirectory": "E:\\LogFiles\\Digital Data\\Rec.API",
"variables": { "RetainedFileCountLimit": 30
"logDirectory": "E:\\LogFiles\\Digital Data\\Rec.API",
"logFileNamePrefix": "${shortdate}.Rec.API"
},
"targets": {
"infoLogs": {
"type": "File",
"fileName": "${logDirectory}\\${logFileNamePrefix}-Info.log",
"maxArchiveDays": 30
},
"warningLogs": {
"type": "File",
"fileName": "${logDirectory}\\${logFileNamePrefix}-Warning.log",
"maxArchiveDays": 30
},
"errorLogs": {
"type": "File",
"fileName": "${logDirectory}\\${logFileNamePrefix}-Error.log",
"maxArchiveDays": 30
},
"criticalLogs": {
"type": "File",
"fileName": "${logDirectory}\\${logFileNamePrefix}-Critical.log",
"maxArchiveDays": 30
}
},
"rules": [
{
"logger": "*",
"level": "Info",
"writeTo": "infoLogs"
},
{
"logger": "*",
"level": "Warn",
"writeTo": "warningLogs"
},
{
"logger": "*",
"level": "Error",
"writeTo": "errorLogs"
},
{
"logger": "*",
"level": "Fatal",
"writeTo": "criticalLogs"
}
]
} }
} }