This post is about using Log4Net with ASP.NET Core for implementing logging. The Apache log4net library is a tool to help the programmer output log statements to a variety of output targets. log4net is a port of the excellent Apache log4j™ framework to the Microsoft® .NET runtime. We have kept the framework similar in spirit to the original log4j while taking advantage of new features in the .NET runtime.
First you need to add the reference of log4net libarary in project.json file. I am using "log4net":"2.0.7". Now you can write code using log4net. I am writing the code in Program.cs file. Unline ASP.NET, log4net doesn’t support the attribute for loading the configuration, so you need to load the configuration manually. Here is a sample log4net configuration file I am using, which will log in a file using FileAppender. I am logging all the information. You can find more information about logging providers and levels in the log4net documentation.
Here is the program.cs file, which gets an instance of the ILog object and the configuration is loaded manually.
The log4net.config file added in the root folder. Now you can run the application, and you see a file with name app.log created in the C:\temp folder. If you look into that you will see only the information we logged is added. But if you want something similar to the ASP.NET Core logging, you need to implement the provider and extension methods yourself.
Here is the implementation, which helps you to log similar to the existing ASP.NET Core logging implementations.
Firstly you need to implement the ILogger interface with Log4Net library. Here is the implementation.
And this logger need to be provided to the logger factory extension using ILoggerProvider implementation. Here is the ILoggerProvider implementation. Most of the code I took from the console logger provider implementation from ASP.NET Core implementation. The configuration parsing is implemented inside this class.
Finally you need ILoggerFactory extension methods, which helps to add Log4Net to the logger factory. Here is the extension method implementation.
And you can use this inside Configure() method.
Now you can run the app again and you can see the log file filled with lot of logging details.
Here is the screenshot of the log file created by log4net.