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");
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With