Search code examples
c#.net-coreserilogserilog-sinks-fileworker-service

Worker service in .NET Core 8 C# Serilog logger : write to file using setting in AppSettings


I want to add Serilog for logging and write the log into text file based setting defined in the appsettings.json config file.

I find challenge since .NET Core 8 it uses

var builder = Host.CreateApplicationBuilder(args);

The sample I get most uses

var builder = Host.CreateDefaultBuilder(args);

I want to define complete settings in appsettings.json and worker service must read from that and behave accordingly.

{
  "Serilog": {
    "WriteTo": [
      { "Name": "File", "Args": { "path": "log.txt", "rollingInterval": "Day" } }
    ]
  }
}

Please help me to provide the config from appsettings.json and program.cs where code is registered.

Found solution

builder.Services.AddSerilog(loggingBuilder => loggingBuilder
        .WriteTo.File(logFilePath, rollingInterval: RollingInterval.Day,
            fileSizeLimitBytes: 10 * 1024 * 1024) // Limit each log file to 10 MB
);

Here I want to log only for Information, Warning. I tried "Where" but it says that method is not available though I have serilog 3.0

And Also I added custom Logger to log Error and critical to SQL Server Database Table via proc. I made that changes it is not working both. It write to file when both are enabled. if I comment serilog the it write to sql server table. Please advise

builder.Services.AddSerilog(loggingBuilder => loggingBuilder

    .WriteTo.File(logFilePath, rollingInterval: RollingInterval.Day,
        fileSizeLimitBytes: 10 * 1024 * 1024) // Limit each log file to 10 MB

);

var connectionString = Configuration.GetSection("ConnectionStrings");
var sqlServerMinimumLogLevel = Configuration.GetValue<LogLevel>("Logging:SqlServerMinimumLevel", LogLevel.Error); // Default to Error

builder.Services.AddLogging(configure =>
{
    configure.AddProvider(new SqlServerLoggerProvider(connectionString.Value, sqlServerMinimumLogLevel) ); // Assuming custom provider implemented
}); 

Another Challenge I face it is write to text file but not writting to database table using custom log provider.

I want both Serilog to write text and use custom log provider to write into database table. Please advise


Solution

  • 1.Install the necessary NuGet packages for Serilog, its sinks for file and console, and the settings configuration:

    dotnet add package Serilog
    dotnet add package Serilog.Sinks.Console
    dotnet add package Serilog.Sinks.File
    dotnet add package Serilog.Settings.Configuration
    dotnet add package Serilog.Extensions.Hosting
    

    2.Create an appsettings.json file with the Serilog configuration settings. Here’s an example of what your appsettings.json might look like:

    {
      "Serilog": {
        "Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
        "MinimumLevel": "Information",
        "WriteTo": [
          { "Name": "Console" },
          { "Name": "File", "Args": { "path": "log.txt" } }
        ],
        "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
        "Properties": {
          "Application": "YourAppName"
        }
      }
    }
    

    3.Configure Serilog in your Program.cs or Startup.cs to use the configuration from appsettings.json:

    var builder = Host.CreateApplicationBuilder(args);
    
    Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(builder.Configuration)
        .CreateLogger();
    
    builder.Logging.ClearProviders();
    builder.Logging.AddSerilog();