diff --git a/dotnet-logging/LogLevelsWithSerilog/LogLevelsWithSerilog/LogLevelsWithSerilog.csproj b/dotnet-logging/LogLevelsWithSerilog/LogLevelsWithSerilog/LogLevelsWithSerilog.csproj index 7d83ebc86e..088667a419 100644 --- a/dotnet-logging/LogLevelsWithSerilog/LogLevelsWithSerilog/LogLevelsWithSerilog.csproj +++ b/dotnet-logging/LogLevelsWithSerilog/LogLevelsWithSerilog/LogLevelsWithSerilog.csproj @@ -1,18 +1,18 @@ - net7.0 + net10.0 enable enable - - - - + + + + + - diff --git a/dotnet-logging/LogLevelsWithSerilog/LogLevelsWithSerilog/Program.cs b/dotnet-logging/LogLevelsWithSerilog/LogLevelsWithSerilog/Program.cs index c56fca9be6..01d30a44c6 100644 --- a/dotnet-logging/LogLevelsWithSerilog/LogLevelsWithSerilog/Program.cs +++ b/dotnet-logging/LogLevelsWithSerilog/LogLevelsWithSerilog/Program.cs @@ -1,4 +1,5 @@ using Serilog; +using Serilog.Core; using Serilog.Events; var configuration = new ConfigurationBuilder() @@ -10,13 +11,17 @@ Log.Information("Web Host started"); var builder = WebApplication.CreateBuilder(args); +// Wrapping the minimum level in a LoggingLevelSwitch lets us change it at +// runtime -- e.g. from an admin endpoint -- with no redeploy and no restart. +var levelSwitch = new LoggingLevelSwitch(LogEventLevel.Information); + builder.Services.AddSerilog(options => { //we can configure serilog from configuration options.ReadFrom.Configuration(configuration); //or we can configure serilog via fluent api - options.MinimumLevel.Information() + options.MinimumLevel.ControlledBy(levelSwitch) .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("System", LogEventLevel.Warning) .WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Information, @@ -44,4 +49,12 @@ name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); +// e.g. POST /admin/log-level/Debug -- flips the minimum level on every sink +// immediately, with no restart. +app.MapPost("/admin/log-level/{level}", (LogEventLevel level) => +{ + levelSwitch.MinimumLevel = level; + return Results.Ok($"Minimum log level set to {level}."); +}); + app.Run(); \ No newline at end of file diff --git a/dotnet-logging/LogLevelsWithSerilog/Tests/LogLevelsWithSerilogTests.csproj b/dotnet-logging/LogLevelsWithSerilog/Tests/LogLevelsWithSerilogTests.csproj index 7c6328c181..4c219929d0 100644 --- a/dotnet-logging/LogLevelsWithSerilog/Tests/LogLevelsWithSerilogTests.csproj +++ b/dotnet-logging/LogLevelsWithSerilog/Tests/LogLevelsWithSerilogTests.csproj @@ -1,7 +1,7 @@ - net7.0 + net10.0 enable enable