Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Log4Net work with ASP.NET Core 3.1 using Dependency Injection?

I am trying to use log4Net in an ASP.NET Core 3.1 application and I am trying to get it to work with Dependency Injection using controllers. I am successfully able to use Log4Net using LogManager.GetLogger(type). Any help would be appreciated.

Here is a sample of the code I am using for logging now:

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

    public HomeController()
    {
        _log.Debug("Test");
    }
}
like image 656
RunningMan Avatar asked Sep 20 '25 20:09

RunningMan


1 Answers

Any services you want to inject into a Controller must be registered in Startup.ConfigureServices(IServiceCollection) (Startup.cs), or in Program.CreateHostBuilder(string []) (Program.cs) usually after CreateDefaultBuilder and ConfigurWebHostDefaults.

You can register the service using the following:

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder => /* ... */)
        .ConfigureLogging(builder =>
        {   // Configuration here:
            builder.SetMinimumLevel(LogLevel.Trace);
            builder.AddLog4Net("log4net.config");
        });

Then, you can inject using the Microsoft.Extensions.Logging.ILogger<T> (where T is the class being logged), which will use Log4Net:

public class HomeController : Controller {
    private readonly ILogger<HomeController> _log;

    // A suitable logger instance is created by the runtime DI:
    public HomeController(ILogger<HomeController> log)
    {
        _log = log;
        _log.Debug("Test");
    }
}

For more information, here is a tutorial.

like image 144
Connor Low Avatar answered Sep 22 '25 12:09

Connor Low