1

I am working on a .net 6 application. I have used Serilog for logging. I have received a request to log the debug logs based on the database settings. Below is my setting table:

Create table ApplicationSettings
(
  Id UNIQUEIDENTIFIER PRIMARY KEY NOT NULL,
  Name VARCHAR(500) NOT NULL,
  [Value] VARCHAR(200) NOT NULL,
  CreatedOn DATETIMEOFFSET,
  Active BIT
)

INSERT INTO ApplicationSettings VALUES(NEWID(),'Log Debug Message','true', GETDATE(),1)
SELECT * FROM ApplicationSettings

If "Log Debug Message is true" in above table then only I have to log the debug messages of Serilog or else I don't have to log the debug message.

Here is my appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=Something;Database=SampleDb;Trusted_Connection=True;MultipleActiveResultSets=true;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Serilog": {
    "Using": [ "Serilog.Enrichers.ClientInfo", "Serilog.Sinks.MSSqlServer" ],
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Warning",
        "System": "Warning",
        "System.Net.Http.HttpClient": "Warning"
      }
    },
    "Enrich": [ "FromLogContext", "WithMachineName", "WithClientIp", "WithClientAgent" ],
    "WriteTo": [
      {
        "Name": "MSSqlServer",
        "Args": {
          "connectionString": "Server=Something;Database=SampleDb;Trusted_Connection=True;MultipleActiveResultSets=true;",
          "sinkOptionsSection": {
            "tableName": "tblLogs",
            "autoCreateSqlTable": true
          },
          "restrictedToMinimumLevel": "Debug",
          "columnOptionsSection": {
            "primaryKeyColumnName": "Id",
            "addStandardColumns": [ "LogEvent", "SourceContext" ],
            "removeStandardColumns": [ "Properties" ],
            "additionalColumns": [
              {
                "ColumnName": "ClientIP",
                "PropertyName": "ClientIp",
                "DataType": "nvarchar"
              }                  
            ]
          }
        }
      }
    ]
  }
}

Program.cs

using Serilog;
using Serilog.Events;

var builder = WebApplication.CreateBuilder(args);


#region Configure serilog

builder.Logging.ClearProviders();
IConfigurationRoot configuration = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json", false, true)
        .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
        .Build();

var logger = new LoggerConfiguration()
                .ReadFrom.Configuration(configuration)
                .MinimumLevel.Override("Microsoft", LogEventLevel.Error)
                .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Error)
                .MinimumLevel.Override("Serilog", LogEventLevel.Error)
                .Enrich.FromLogContext()
                .Enrich.WithClientIp()
                .Enrich.WithClientAgent()
                .CreateLogger();

Log.Logger = logger;
builder.Logging.AddSerilog(logger);
builder.Host.UseSerilog();

#endregion


// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if(app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else if(app.Environment.IsStaging() || app.Environment.IsProduction())
{
    app.UseExceptionHandler("/Error");
}

app.UseSerilogRequestLogging();

app.UseStaticFiles();
app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

HomeController.cs

    public class HomeController : Controller
    {     
        public IActionResult Index()
        {            
            return View();
        }

        public IActionResult Privacy()
        {
            //Here If "Log Debug Message is set to true" in "ApplicationSettings" table
            //then only log debug message of Serilog or else don't log.
            Log.Debug("Started executing Privacy");
            try
            {
                int a = 1;
                int b = 0;
                int c = a / b;
            }
            catch (Exception ex)
            {
                Log.Error(ex, ex.Message);
            }

            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }

Can anybody help me on this? thanks.

Shaksham Singh
  • 491
  • 1
  • 5
  • 19
  • Can anybody help me on this? I found similar example matching my requirement here https://stackoverflow.com/questions/52995755/is-it-possible-to-elegantly-configure-serilog-with-if-statements but not sure how to achieve in my case. I need to fetch the setting from my DB and then as explained above. – Shaksham Singh Oct 05 '22 at 15:49

0 Answers0