3

I am using below code for accessing the Serilog for non Host based Console application..I have two requirement to achieve.

I should be able to access MS extension Logger in all the other classes once Serilog is initialized. We should be able to see the logging statement after each logging line executed.. I am using below code.

Program.cs

private static void main()
    {
        var configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json")
            .Build();

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

        Log.Logger.Information("hello");  //it's not printing the hello in console window.
    }

appsettings.json

    "Serilog": {
    "MinimumLevel": "Verbose",
    "WriteTo": [
        {
            "Name": "Async",
            "Args": {
                "configure": [
                    {
                        "Name": "Console",
                        "Args": {
                            "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console",
                            "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:j}{NewLine}{Properties:j}{NewLine}{Exception}"
                        }
                    },
                    {
                        "Name": "File",
                        "Args": {
                            "restrictedToMinimumLevel": "Warning",
                            "path": "Logs\\log.txt",
                            "rollingInterval": "Day",
                            "fileSizeLimitBytes": 10240,
                            "rollOnFileSizeLimit": true,
                            "retainedFileCountLimit": 30
                        }
                    }
                ]
            }
        }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName", "WithExceptionDetails" ],
    "Properties": {
        "ApplicationName": "SampleApp",
        "Environment": "Int"
    }
}

}```

2 Answers2

0

Your configuration is OK.

Your code misses the call to Log.CloseAndFlush();
See the documentation.

Your code should look like below.

private static void main()
{
    var configuration = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json")
        .Build();

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

    Log.Logger.Information("hello");
    
    Log.CloseAndFlush();
}
pfx
  • 20,323
  • 43
  • 37
  • 57
  • Thanks for input .. but do we really need closeandFlush because for console app if we have written the logs at a particular line so it should logging to console window once line is executed not after calling closenadflush so that it will log at the last .. – Sachin Agarwal Mar 04 '22 at 11:58
  • I tend to say this one is just needed here to clear any buffered log entries. The example above is too small to show any output at runtime because the app closes immediately. – pfx Mar 04 '22 at 12:04
  • You might consider to not include the `Console` log in the `WriteTo.Async`. As the documentation - linked in my answer - says that it is mostly useful for I/O based sinks, e.g. `File` and `RollingFile`. – pfx Mar 04 '22 at 12:53
0

The problem is with your appsettings.json file. The "write to console" configuration seems to be at the wrong level. Your code logs successfully to the console using this simplified version:

{
  "Serilog": {
    "MinimumLevel": "Verbose",
    "WriteTo": [
      {
        "Name": "Console",
        "Args": {
          "theme": "Serilog.Sinks.SystemConsole.Themes.AnsiConsoleTheme::Code, Serilog.Sinks.Console",
          "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:j}{NewLine}{Properties:j}{NewLine}{Exception}"
        }
      }
    ]
  }
}
Tawab Wakil
  • 1,737
  • 18
  • 33