Skip to content
DUONG Phu-Hiep edited this page Nov 22, 2019 · 6 revisions

log4net is complicate to configure. You will have to do several steps to be able to use it in a new project.

It is the reason why I made the ToolsPack.Log4net which provides a Log4netQuickSetup class to do the "boring" work, and help you to quickly got log4net working in your new project (or unit test project).

Unfortunately all of this have not yet available on .NetCore (the future of .NET framework)

Fortunately, I discover a better / quicker way to get log file in a new .NET and .NetCore project:

Go to your new .NET or .NetCore project, do you want some logs?

Step 1) Use nuget to install/add these packages to your project

Step 2) Setup in your code

//once time config
Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .Enrich.FromLogContext()
                .WriteTo.Console()  //write log to console, delete it if you don't want to
                .WriteTo.RollingFile("./logs/myproject-{Date}.log") //write log to a file
                .CreateLogger();

Log.Information("Here some logs");

My above setup will write log message to both Console and log file.

=> You got logs in your project with no hassle!

Quick snippets

Install packages

dotnet add package Serilog
dotnet add package Serilog.Sinks.Console
dotnet add package Serilog.Sinks.RollingFile

Use Serilog in xunit test

dotnet add package Serilog.Sinks.Xunit2
using Xunit;
using Xunit.Abstractions;
using Serilog;

public class SomethingTest
{
  public SomethingTest(ITestOutputHelper output)
  {
    Log.Logger = new LoggerConfiguration()
      .MinimumLevel.Debug()
      .Enrich.FromLogContext()
      .WriteTo.Xunit(output, outputTemplate: "[{Timestamp:HH:mm:ss,fff} {Level:u3}] {Message:lj}{NewLine}{Exception}")  //write log to xunit output
      .CreateLogger();
  }
  
  [Fact]
  public void FuncTest()
  {
    Log.Information("Here some logs {0} {@object}", foo, bar);
  }
}

Use Serilog in ASP.NET core

dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Settings.Configuration
dotnet add package Serilog.Sinks.RollingFile
public class Program
{
  public static void Main(string[] args)
  {
    CreateWebHostBuilder(args).Build().Run();
  }

  public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
      .UseStartup<Startup>()
      .UseSerilog(
        (hostingContext, loggerConfiguration) => 
          loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration)
          //.Enrich.WithExceptionDetails() //TODO: add an Exceptions enricher https://github.com/RehanSaeed/Serilog.Exceptions
          //.MinimumLevel.Override("Microsoft", LogEventLevel.Warning // note: we can also use a LoggingLevelSwitch here or in the configuration file in order to change this value with a remote api call
        );
}

appsetting.json

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.RollingFile" ],
    "MinimumLevel": {
      "Default": "Debug",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "Enrich": [ "FromLogContext" ],
    "WriteTo": [
      {
        "Name": "RollingFile",
        "Args": {
          "pathFormat": "./logs/mrq-{Date}.log",
          "outputTemplate": "{Timestamp:HH:mm:ss,fff} {Level:u3} {Message:lj}{NewLine}{Exception}"
        }
      }
    ]
  }
}

Use Serilog in Console App

You can configure Serilog in code

const string OutputTemplate = "{Timestamp: HH:mm:ss.fff} {Level:u3} {Message:lj}{NewLine}{Exception}";
Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .Enrich.FromLogContext()
    .WriteTo.Console(outputTemplate: OutputTemplate)  //write log to console
    .WriteTo.RollingFile("./logs/{Date}.log", outputTemplate: OutputTemplate) //write log to a file
    .CreateLogger();

Or you can configure Serilog in the app settings

dotnet add package Serilog.Settings.AppSettings

app.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <appSettings>
        <add key="serilog:minimum-level" value="Debug" />

        <add key="serilog:using:Console" value="Serilog.Sinks.Console" />
        <add key="serilog:write-to:Console" />
        <add key="serilog:write-to:Console.outputTemplate" value="{Timestamp: HH:mm:ss.fff} {Level:u3} {Message:lj}{NewLine}{Exception}" />

        <add key="serilog:using:RollingFile" value="Serilog.Sinks.RollingFile" />
        <add key="serilog:write-to:RollingFile.pathFormat" value="./logs/{Date}.txt" />
        <add key="serilog:write-to:RollingFile.outputTemplate" value="{Timestamp: HH:mm:ss.fff} {Level:u3} {Message:lj}{NewLine}{Exception}" />
    </appSettings>
</configuration>

then in Program.cs

Log.Logger = new LoggerConfiguration()
            .ReadFrom.AppSettings()
            .CreateLogger();