Skip to content
DUONG Phu-Hiep edited this page Oct 28, 2018 · 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}"
        }
      }
    ]
  }
}