Search code examples
.net.net-corelog4netlog4net-configuration

Simplest correct way to configure log4net for a .Net Core 3.1 application


I am struggling with understanding the simplest way to configure log4net to use in a .Net Core 3.1 application. The application is using log4net 2.0.8. So:

Is there a way to use the application.runtimeconfig.json file to configure to do this? If so, what code would I add to the application to tell it to use these settings - something like:

log4net.Config.XmlConfigurator.Configure();

If this is not possible, then what's the simplest way to add a configuration file, say log4net.xml, and tell the application to use this?

I want to direct all of the logging to a file for the moment, say Temp.log. I've looked at many log4net pages, but they either talk about using Assembly.Info.cs which does not exist in new .Net Core 3.1 projects, or seem to programmatically set the log4net configuration which I'd like to avoid. I was expecting this to be easy, so apologies if I have missed an obvious approach.


Solution

  • Editing my answer a little to be clear that Core does NOT include a normal file logger out of the box. My bad. (as of 5/19/2020)

    I would recommend using the logging extensions from Microsoft instead of log4net, but this should do for you. Core now comes with a logger and it's pretty nice and plugs in easy for DI, and uses appsettings.json. I can provide a sample of that too if you want. But here's log4net basic example.

    Sample console app that loads config from a file (file set to Copy Always)

    using log4net.Repository;
    using System;
    using System.IO;
    using System.Reflection;
    
    namespace ConsoleApp1Core
    {
        class Program
        {
            private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    
            static void Main(string[] args)
            {
                try
                {
    
                    ILoggerRepository repository = log4net.LogManager.GetRepository(Assembly.GetCallingAssembly());
    
                    var fileInfo = new FileInfo(@"log4net.config");
    
                    log4net.Config.XmlConfigurator.Configure(repository, fileInfo);
    
                    log.Info("test");
    
                    Console.WriteLine("press any key");
                    Console.ReadLine();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine("Press any key to exit");
                    Console.ReadLine();
                }
            }
        }
    }