Skip to content

DRNJ

Light at the end of the Technology Tunnel

  • Home
  • About
  • Contact
DRNJ

Serilog And .Net Core 3.1

The Problem

I found configuring Serilog for .Net Core quite complex and poorly documented. All I wanted to do was to pipe log messages to a text file.

The Solution

After some searching I found this project.

The following code was added to Program.cs

public static void Main(string[] args)
{ 
CreateHostBuilderWithSimpleSerilog(args).Build().Run();
}

public static IHostBuilder CreateHostBuilderWithSimpleSerilog(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging((context, builder) =>
{
//----------------------------------------------------------------------
// Simple SeriLog |
// Using https://github.com/serilog/serilog-extensions-logging-file |
//----------------------------------------------------------------------
builder.AddFile(context.Configuration.GetLoggerConfiguration());
})
.ConfigureWebHostDefaults(webBuilder =>
{
if (bool.Parse(Environment.GetEnvironmentVariable("USE_HTTP_SYS") ?? "false"))
{
webBuilder.UseHttpSys(options =>
{
options.Authentication.Schemes = AuthenticationSchemes.None;
options.Authentication.AllowAnonymous = true;
});
}
webBuilder.UseStartup<Startup>();
});

Along with

 public static class StartupConfiguration
    {

        public static IConfigurationSection GetLoggerConfiguration(this IConfiguration config)
        {
            return config.GetSection("Logging");
        }

        public static T Get<T>(this IConfiguration config, string name)
        {
            return config
                 .GetSection(name)
                 .Get<T>();
        }
    }

And then the Appsettings.json section for logging

 

"Logging": {
"OutputTemplate": "{Timestamp:o} {RequestId,13} [{Level:u3}] {Message} Properties: {Properties:j} ({EventId:x8}){NewLine}{Exception}",
"PathFormat": "Logs/MyLog-{Date}.log",
"MinimumLevel": "Information",
"LogLevel": {
"Default": "Warning",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Warning",
"Microsoft.EntityFrameworkCore": "Warning"
}
}

 

And Voila. Logging to file works and Dependency Injection of Serilog is wired up too.

.NET Core

Idealist by NewMediaThemes