How to use log4net in Asp.net core 2.0

k11k2 picture k11k2 · Sep 12, 2017 · Viewed 99k times · Source

I configure log4net in my asp.net core 2.0 application as mentioned in this article LINK

program.cs

public static void Main(string[] args)
{
    var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
    XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));

    BuildWebHost(args).Run();
}

HomeController

public class HomeController : Controller
{
    private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(HomeController));

    public IActionResult Error()
    {
        log.Info("Hello logging world!");
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}

log4net.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <log4net>
    <root>
      <level value="ALL" />
      <appender-ref ref="RollingFile" />
    </root>
    <appender name="RollingFile" type="log4net.Appender.FileAppender">
      <file value="‪C:\Temp\app.log" /> 
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%-5p %d{hh:mm:ss} %message%newline" />
      </layout>
    </appender>
  </log4net>
</configuration>

Unlucky!, I didn't see any file generated in ‪C:\Temp\app.log directory. What would be the mistake? how to configure log4net for asp.net core 2.0?

Answer

Jan Muncinsky picture Jan Muncinsky · Jun 1, 2018

There is a third-party log4net adapter for the ASP.NET Core logging interface.

Only thing you need to do is pass the ILoggerFactory to your Startup class, then call

loggerFactory.AddLog4Net();

and have a config in place. So you don't have to write any boiler-plate code.

More info here