Search code examples
serilog

Why serilog not logging to file?


"WriteTo": [
      {
        "Name": "File"
      },
      {
        "Name": "File",
        "Args": {
          "configureLogger": {
            "WriteTo": [
              {
                "Name": "File",
                "Args": {
                  "path": "Logs/Error/applog.log",
                  "outputTemplate": "{Timestamp:o} [Thread:{ThreadId}] [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
                  "rollingInterval": "Day",
                  "retainedFileCountLimit": 7
                }
              }
            ]
          }
        }
      }

I have this in my app setting.json file?

Why serilog not writting to "path": "Logs/Error/applog.log", ?

var configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build();

        var Logger = new LoggerConfiguration()
          .ReadFrom.Configuration(configuration)
          .CreateLogger();

        Logger.Information("Hello, world!");

I have this setting file ?

{
  "Logging": {
    "Serilog": {
      "WriteTo": [
        {
          "Name": "File",
          "Args": {
            "path": "Logs/Error/applog.log",
            "outputTemplate": "{Timestamp:o} [Thread:{ThreadId}] [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
            "rollingInterval": "Day",
            "retainedFileCountLimit": 7
          }
        }
      ]
    },
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "HrSoultion": "server=.;database=Maqta;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True"
  }
}

Solution

  • Your configuration in appsettings.json doesn't seem to be correct.

    If you provide this configuration, it should work:

    {
      "Serilog": {
        "WriteTo": [
          {
            "Name": "File",
            "Args": {
              "path": "Logs/Error/applog.log",
              "outputTemplate": "{Timestamp:o} [Thread:{ThreadId}] [{Level:u3}] ({SourceContext}) {Message}{NewLine}{Exception}",
              "rollingInterval": "Day",
              "retainedFileCountLimit": 7
            }
          }
        ]
      }
    }
    

    My result:

    Result


    For reference, I used .NET 6 and these NuGet packages:

      <ItemGroup>
        <PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.0" />
        <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
        <PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" />
        <PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
      </ItemGroup>
    
    

    Links: