Log4net is an easy to use, reliable, fast, popular, extensible, and open source library for logging data to various configured log targets Credit: Greg Lobinski When working on applications, you may often want to log application data that may include, the sequence of events in your application, user actions or even errors when they occur. There are many logging frameworks that you can use, but log4net is by far one of the most popular logging frameworks for use with applications built or developed in .NET. It is an open source library (a port of the popular log4j open source library for Java) that can be used to log application data to different log targets in .NET. Installing log4net The easiest and quickest way to get started using log4net is by installing it through the NuGet Package Manager. Assuming that you have created a console application project in Visual Studio, you can install log4net via NuGet Manager, by following these steps. In the “Solution Explorer Window,” select and right click on your project Click “Manage NuGet Packages…” Click “Online” and then type log4net in the search box Select the log4net package you would like to install Click “Install” to start the installation process As of this writing, the latest stable release of log4net is 2.0.5. Once log4net has been installed via the NuGet Package Manager, you would observe the log4net assembly added as a reference to your project. Configuring log4net Now that the log4net package has been installed successfully, add the following line to the AssemblyInfo.cs file in the Properties folder of your project. If this is not specified, the configuration settings would not be considered. [assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)] Alternatively, you can also mention the same in the app.config or the web.config file. [assembly: log4net.Config.XmlConfigurator(Watch = true)] If your log4net configuration metadata resides in some other file (i.e., other than web.config or app.config files), you can specify the following instead. [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)] The next step is to specify the necessary configuration details for log4net in the app.config or the web.config file in your application. Assuming that you are using a console application project, add a configuration section named “log4net” in the app.config file as shown below. <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections> Now, add the section “” after the element in your app.config file. Next, inside the “” section, place the configuration details as shown in the code snippet given below. <log4net> <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender"> <param name="File" value="C:ProjectsPersonalIDGIDG.log"/> <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> <appendToFile value="true" /> <rollingStyle value="Size" /> <maxSizeRollBackups value="10" /> <maximumFileSize value="1MB" /> <staticLogFileName value="true" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %level %logger - %message%newline" /> </layout> </appender> <root> <level value="ALL" /> <appender-ref ref="LogFileAppender" /> </root> </log4net> That’s all you need to do to configure log4net. Let’s now explore how we can use it in our code. The element is used to specify the name and type of the logger to be used. In this example we are using the rolling file appender. However, there are many other types of appenders available, i.e., AdoNetAppender, AspNetTraceAppender, ConsoleAppender, etc. Here is the full list and how to configure other appenders. Using log4net In your class, create a reference to ILog by making a call to the GetLogger static method of the LogManager class as shown in the code snippet given below. private static readonly log4net.ILog log = log4net.LogManager.GetLogger (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); You can now use the instance named log to log data to the configured targets. The following code snippet illustrates how you can now take advantage of the log instance to log data. log.Debug("This is a Debug message"); log.Info("This is a Info message"); log.Warn("This is a Warning message"); log.Error("This is an Error message"); log.Fatal("This is a Fatal message"); Here’s a complete code listing that shows how you can log your exception message in a text file using log4net. class Program { static readonly log4net.ILog log = log4net.LogManager.GetLogger (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); static void Main(string[] args) { try { throw new Exception("This is test message..."); } catch(Exception ex) { log.Error(ex.Message); } Console.Read(); } } After you execute the above program, a text file named IDG.log will be created and the exception message specified with be logged along with the timestamp. Note that you can also use log4net programmatically, i.e., configure log4net programmatically sans the need of the configuration we discussed earlier. Related content how-to How to use FastEndpoints in ASP.NET Core Take advantage of the free open-source FastEndpoints library to build fast and lean APIs in your ASP.NET Core applications. By Joydip Kanjilal Jul 11, 2024 7 mins Microsoft .NET C# Development Libraries and Frameworks how-to How to use Refit to consume APIs in ASP.NET Core Take advantage of Refit REST library to simplify API consumption and make your code cleaner, more efficient, and easier to maintain. By Joydip Kanjilal Jul 04, 2024 10 mins C# Microsoft .NET Software Deployment how-to When to use an abstract class vs. interface in C# Understanding the differences between an abstract class and interface is key to designing loosely coupled and extensible applications. By Joydip Kanjilal Jun 20, 2024 10 mins Small and Medium Business Microsoft .NET C# how-to 6 security best practices for ASP.NET Core Learn the best practices and built-in safeguards for preventing attacks and protecting sensitive data in your ASP.NET Core web applications. By Joydip Kanjilal Jun 07, 2024 6 mins C# Microsoft .NET Web Development Resources Videos