How to use log4net in Asp.net core 2.0

110,976

Solution 1

I am successfully able to log a file using the following code

public static void Main(string[] args)
{
    XmlDocument log4netConfig = new XmlDocument();
    log4netConfig.Load(File.OpenRead("log4net.config"));
    var repo = log4net.LogManager.CreateRepository(Assembly.GetEntryAssembly(),
               typeof(log4net.Repository.Hierarchy.Hierarchy));
    log4net.Config.XmlConfigurator.Configure(repo, log4netConfig["log4net"]);

    BuildWebHost(args).Run();
}

log4net.config in website root

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
    <file value="C:\Temp\" />
    <datePattern value="yyyy-MM-dd.'txt'"/>
    <staticLogFileName value="false"/>
    <appendToFile value="true"/>
    <rollingStyle value="Date"/>
    <maxSizeRollBackups value="100"/>
    <maximumFileSize value="15MB"/>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level App  %newline %message %newline %newline"/>
    </layout>
  </appender>
    <root>
      <level value="ALL"/>
      <appender-ref ref="RollingLogFileAppender"/>
    </root>
</log4net>

Solution 2

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

Solution 3

Still looking for a solution? I got mine from this link .

All I had to do was add this two lines of code at the top of "public static void Main" method in the "program class".

 var logRepo = LogManager.GetRepository(Assembly.GetEntryAssembly());
 XmlConfigurator.Configure(logRepo, new FileInfo("log4net.config"));

Yes, you have to add:

  1. Microsoft.Extensions.Logging.Log4Net.AspNetCore using NuGet.
  2. A text file with the name of log4net.config and change the property(Copy to Output Directory) of the file to "Copy if Newer" or "Copy always".

You can also configure your asp.net core application in such a way that everything that is logged in the output console will be logged in the appender of your choice. You can also download this example code from github and see how i configured it.

Solution 4

You need to install the Microsoft.Extensions.Logging.Log4Net.AspNetCore NuGet package and add a log4net.config-file to your application. Then this should work:

public class Program
{
    private readonly ILogger<Program> logger;

    public Program()
    {
        var services = new ServiceCollection()
            .AddLogging(logBuilder => logBuilder.SetMinimumLevel(LogLevel.Debug))
            .BuildServiceProvider();


        logger = services.GetService<ILoggerFactory>()
            .AddLog4Net()
            .CreateLogger<Program>();
    }

    static void Main(string[] args)
    {
        Program program = new Program();

        program.Run();

        Console.WriteLine("\n\nPress any key to continue...");
        Console.ReadKey();
    }

    private void Run()
    {
        logger.LogInformation("Logging is working");
    }
}

Solution 5

Following on Irfan's answer, I have the following XML configuration on OSX with .NET Core 2.1.300 which correctly logs and appends to a ./log folder and also to the console. Note the log4net.config must exist in the solution root (whereas in my case, my app root is a subfolder).

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
      <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date %-5level %logger - %message%newline" />
      </layout>
  </appender>
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
    <file value="logs/" />
    <datePattern value="yyyy-MM-dd.'txt'"/>
    <staticLogFileName value="false"/>
    <appendToFile value="true"/>
    <rollingStyle value="Date"/>
    <maxSizeRollBackups value="100"/>
    <maximumFileSize value="15MB"/>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level App  %newline %message %newline %newline"/>
    </layout>
  </appender>
    <root>
      <level value="ALL"/>
      <appender-ref ref="RollingLogFileAppender"/>
      <appender-ref ref="ConsoleAppender"/>
    </root>
</log4net>

Another note, the traditional way of setting the XML up within app.config did not work:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net> ...

For some reason, the log4net node was not found when accessing the XMLDocument via log4netConfig["log4net"].

Share:
110,976
k11k2
Author by

k11k2

Updated on January 08, 2021

Comments

  • k11k2
    k11k2 over 3 years

    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?

  • The Muffin Man
    The Muffin Man almost 6 years
    The root gets setup properly, but any child loggers have null for level, and don't have an appenders set up.
  • Irfan Ashraf
    Irfan Ashraf almost 6 years
    I am unaware of child loggers, can you share code and example so I can include in my answer.
  • Shane Kenyon
    Shane Kenyon almost 6 years
    Caveat, the debugger looks for the file in the sub-folder, not the root.
  • Przemek
    Przemek over 5 years
    Ok, but how do you use this logger? I did not find examples on usage in the provided link eaither. Examples?
  • Jan Muncinsky
    Jan Muncinsky over 5 years
    @Przemek. Once you do this, then inject ILogger or ILogger<T> where ever you need and all calls will be forwarded to log4net implementation. docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/…
  • Radek Strugalski
    Radek Strugalski over 5 years
    Still not working (refering to ASP.NET Core 2.1 framework). Log file is not created. log4.net.config is read, but appenders do not seem to be created (log has empty list of Appenders). XmlConfigurator is called. log4net.configis exactly as in the original post. Any ideas?
  • techjunkie
    techjunkie over 4 years
    You can look at the entire implementation at techjunkieblog.com/2019/08/…
  • Ranvijay Singh
    Ranvijay Singh over 4 years
    Does EventLogAppender support is provided for .NetCore3.0 in Log4Net?
  • David Thielen
    David Thielen over 4 years
    Is this still the best (and needed) solution on .NET Core 3.0?
  • ckapilla
    ckapilla almost 4 years
    worked great for me; no need to mess with ServiceCollections as shown in the next answer.
  • red888
    red888 over 3 years
    how do you have multiple log4net config files base on dev or prod and switch between them?
  • ahsant
    ahsant over 3 years
    Remove <configuration> section from log4net.config. If you are using existing log4net.config
  • WillC
    WillC over 3 years
    For .Net Core 3.1, the connectionType has apparently changed to: <connectionType value="Microsoft.Data.SqlClient.SqlConnection, Microsoft.Data.SqlClient, Version=1.0.0.0,Culture=neutral,PublicKeyToken=23ec7fc2d6eaa‌​4a5"/>
  • WillC
    WillC over 3 years
    This worked for me. See Darios answer on: stackoverflow.com/questions/60897550/…