Serilog not writing to the file with Configuration loaded from appsettings.json in Console CORE 3 App

Viewed 10031
ASP.NET CORE 3.1 Worker Service Application.

Packages

"Microsoft.EntityFrameworkCore.Design" Version="3.1.3"

PackageReference Include="Microsoft.Extensions.Hosting" Version="3.1.3"

PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="3.1.3"

PackageReference Include="Serilog.AspNetCore" Version="3.2.0"

PackageReference Include="Serilog.Extensions.Hosting" Version="3.0.0"

Serilog writing to the file with hard-coded LoggerConfiguration but not working from Config loaded from appsettings.json

Here is application code

public static class Program
{
    public static IConfigurationRoot Configuration { get; set; }
    private static string _environmentName;

    public static void Main(string[] args)
    {
        var hostBuilder = CreateHostBuilder(args).Build();
        //Log.Logger = (Configuration["Logging:LogLevel:Default"] == "Debug")? 
        //    new LoggerConfiguration()
        //    .MinimumLevel.Debug()
        //    .WriteTo.Console()
        //    .WriteTo.File(path: Path.Combine("C:/LogFiles", "OA-EmailService-.log"),
        //        rollingInterval: RollingInterval.Day, shared: true, flushToDiskInterval: TimeSpan.FromSeconds(10))
        //    .CreateLogger()
        //    :
        //    new LoggerConfiguration()
        //        .WriteTo.Console()
        //        .WriteTo.File(path: Path.Combine("C:/LogFiles", "OA-EmailService-.log"),
        //            rollingInterval: RollingInterval.Day, shared: true, flushToDiskInterval: TimeSpan.FromSeconds(10))
        //        .CreateLogger()
        //    ;
        Log.Logger = new LoggerConfiguration()
            .ReadFrom.Configuration(Configuration)
            .CreateLogger();

        try
        {
            Log.Information("APP:App started");
            hostBuilder.Run();
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "APP:App startup failed");
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureLogging((hostingContext, config) =>
            {
                config.ClearProviders();  //Disabling default integrated logger
                _environmentName = hostingContext.HostingEnvironment.EnvironmentName;
            })
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                Configuration = new ConfigurationBuilder()
                    .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                    //.AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json",
                    //    optional: false, 
                    //    reloadOnChange: true)
                    .AddEnvironmentVariables()
                    .Build();
            })
            .UseSerilog()
            .UseWindowsService()
            .ConfigureServices((hostContext, services) => { services.AddHostedService<Worker>(); });
}

Here is appsettings.json

    {
      "Serilog": {
        "MinimumLevel": "Debug",
        "WriteTo": [
          {
            "Name": "Console",
            "Args": {
              "outputTemplate": "===> {Timestamp:HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}"
            }
          },
          {
            "Name": "RollingFile",
            "Args": {
              "pathFormat": "C:/LogFiles/OA-EmailService-.log",
              "outputTemplate": "===> {Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level}] {Message}{NewLine}{Exception}"
            }
          }
        ]
      }
    }

Interestingly that the part for Console sink is working well, it is just problem with file. How can I force serilog to write into the file?

1 Answers

1) Do you have the proper sink package installed? You're showing the arguments for the (deprecated) rolling file sink at https://github.com/serilog/serilog-sinks-rollingfile / https://www.nuget.org/packages/Serilog.Sinks.RollingFile/, which would have to actively be installed in order for the appsettings value to be run.

The syntax for the preferred Serilog.Sinks.File package would be as:

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

2) Does the folder you've specified exist and does the executable have permission to write to the folder? It may be silently failing if the attempt to write to the folder path isn't allowed by the file system.

Related