Install and configure log4net in C# .NET

Last updated on 29th September 2022

Log4net is a logging tool developed by Apache for the .Net platform. It is fast, flexible and one of the most popular logging framework used by .Net developers to write log messages to a variety of targets such as file, event logs, database, etc., Log4Net is a port of the log4j library which is a hugely popular logging library for Java. This article illustrates how to install and configure log4net in a C# .Net project.

Install log4Net

You can install log4net from the NuGet Package Manager GUI or from the Package Manager Console.

To install log4net from GUI,

  • From Visual Studio IDE, click Tools → Nuget Package Manager → Manage NuGet Packages for solution. Alternatively you can right click a project in Solution Explorer and click Manage NuGet Packages..

  • Click Browse then type log4net in the search box.

  • Select log4net from the search results.

  • Select a Project where you want to install log4net.

  • Select the version of log4net and click Install.

To install log4net from Package manager Console,

  • Open Package Manager Console. From Visual Studio IDE, click Tools → Nuget Package Manager → Package Manager Console.

  • Select Default Project in the Project Manager Console.

  • Run the Install-Package command.

    PM> Install-Package log4net 
    

    The above command will install the latest version of log4net in the default project. You can use the -version parameter to install a specific version of log4net.

    PM> Install-Package log4net -version 2.0.15
    

Configure log4net

Log4net can be fully configured programmatically but typically it is configured using configuration files that are in XML format. The XML configuration can be embedded in application configuration files - app.config or web.config or it can be stored in a separate file that is read directly.

Here is an example of a valid configuration file

<?xml version="1.0" encoding="utf-8" ?>
 <log4net>
   <root>
      <level value="ALL" />
      <appender-ref ref="LogFileAppender" />
    </root>
    <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="MyLog.log" />
       <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %level %logger - %message%newline" />
      </layout>
    </appender>
  </log4net>

If the log4net configuration is held in your application's .config files, these files should also have a configSections element that defines the log4net section, as shown in the example below.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
 
 <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
 </configSections>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
  </startup>
 
 <log4net>
   <root>
     <level value="ALL" />
     <appender-ref ref="LogFileAppender" />
   </root>
   <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="MyLog.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>
</log4net>

</configuration>

Initialize and Load Configuration

Before you can use log4net in your class, you need to initialize and load a valid XML configuration. Log4net comes with a configuration reader log4net.Config.XmlConfigurator that can parse a XML DOM and use that to configure log4net. The Configure() method of XmlConfigurator can be called to automatically configure log4net with the configuration that is applications .config file.

log4net.Config.XmlConfigurator.Configure();

If the configuration is in a separate file then you can pass a FileInfo object to the Configure() method as shown in the code snippet below.

FileInfo configFile = new FileInfo("log.config");
XmlConfigurator.Configure(configFile);

XmlConfigurator also has ConfigureAndWatch() method that can be used to watch a config file and reload the config if it changes. This method can watch external files only, not application config files. See example below.

FileInfo cf = new FileInfo("log4net.config");
XmlConfigurator.ConfigureAndWatch(cf);

Instead of calling XmlConfigurator.Configure() you could also initialize log4net using the assembly level attribute.

Open AssemblyInfo.cs file under project's Properties and add the following line to initialize log4net with config in app.config

[assembly: log4net.Config.XmlConfigurator()]

To could also specify a file name to load the configuration from and also set the Watch flag to instruct log4net to watch and reload the configuration each time it is changed.

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

Declaring and using logger

After the log4net system is initialized,the next step is to declare a logger and start logging.

The following example demonstartes how to use log4Net in C# Windows Forms application.

using System;
using System.Windows.Forms;
using log4net;
using log4net.Config;

namespace WindowsFormsApp1
{

    public partial class Form1 : Form
    {
       // Declare a logger
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Initialize log4net
            XmlConfigurator.Configure();
            
            // Log a message 
            log.Info("Logging initialized");
        }
    }
}

Log4net is a very powerful and flexible logging tool. You can configure multiple loggers and each logger can have multiple appenders. You can define the layout of log messages and also create filters to remove certain messages. These features are discussed in the next post.


Post a comment

Comments

Aykut ARICIO?LU | February 2, 2023 8:13 AM |

Hi, System.IO.FileNotFoundException: 'Could not load file or assembly 'log4net, Version=2.0.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a' or one of its dependencies. The system cannot find the file specified.' how can i solve this problem ?

Srikanth | February 6, 2023 1:16 PM |

what is the version of log4net that you installed? Is it 2.0.15 ?