How to use log4net for logging in C#

By FoxLearn 7/19/2024 2:05:03 AM   13.28K
Using log4net in C# Windows Forms applications is a great way to incorporate logging functionality into your application for debugging and error tracking purposes.

How to use log4net in C#

Open your Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "Logging" and then click OK

You need to install the log4net package in your project by right-clicking on your project select Manage NuGet Packages -> Search log4net -> Install

install log4net

You can do this via NuGet Package Manager Console by running the following command

Install-Package log4net

Log4net is a tool to help the programmer output log statements to a variety of output targets. In case of problems with an application, it is helpful to enable logging so that the problem can be located. With log4net it is possible to enable logging at runtime without modifying the application binary. The log4net package is designed so that log statements can remain in shipped code without incurring a high performance cost.

At the same time, log output can be so voluminous that it quickly becomes overwhelming. One of the distinctive features of log4net is the notion of hierarchical loggers. Using these loggers it is possible to selectively control which log statements are output at arbitrary granularity. 

Log4net is designed with two distinct goals in mind: speed and flexibility

Drag and drop Button controls from the Visual Studio toolbox onto your form designer, then you can design your form as below

log4net c#

In this example, we will save log4net into database, so you need to create a Log table as shown below.

CREATE TABLE [dbo].[Log] (
    [Id] [int] IDENTITY (1, 1) NOT NULL,
    [Date] [datetime] NOT NULL,
    [Thread] [varchar] (255) NOT NULL,
    [Level] [varchar] (50) NOT NULL,
    [Logger] [varchar] (255) NOT NULL,
    [Message] [varchar] (4000) NOT NULL,
    [Exception] [varchar] (2000) NULL
)

Create a configuration file (typically named log4net.config or log4net.xml) where you define the logging configuration. This is typically an XML file where you specify the logging configuration. You can add the log4net config into your app.config file.

Below is a sample XML configuration for logging to a SQL Server database:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net>
    <root>
      <level value="ALL"></level>
      <appender-ref ref="AdoNetAppender"></appender-ref>
    </root>
    <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
      <bufferSize value="1" />
      <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      <connectionString value="data source=.;initial catalog=dblog;integrated security=false;persist security info=True;User ID=sa;Password=123@qaz" />
      <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />
      <parameter>
        <parameterName value="@log_date" />
        <dbType value="DateTime" />
        <layout type="log4net.Layout.RawTimeStampLayout" />
      </parameter>
      <parameter>
        <parameterName value="@thread" />
        <dbType value="String" />
        <size value="255" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%thread" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@log_level" />
        <dbType value="String" />
        <size value="50" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%level" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@logger" />
        <dbType value="String" />
        <size value="255" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%logger" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@message" />
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%message" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@exception" />
        <dbType value="String" />
        <size value="2000" />
        <layout type="log4net.Layout.ExceptionLayout" />
      </parameter>
    </appender>
  </log4net>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
</configuration>

Don't forget to modify the connectionString value with your SQL Server connection string, and adjust the commandText value according to your database schema.

Log4net log to database example

In your C# code, configure log4net to use this configuration file. Add this line early in your application initialization:

log4net.Config.XmlConfigurator.Configure(new FileInfo("path/to/log4net.config"));

Make sure to replace "path/to/log4net.config" with the actual path to your log4net configuration file.

If you don't use the log4net.config you can config like this

log4net.Config.XmlConfigurator.Configure();

Now you can start logging messages from anywhere in your code. Import the log4net namespace (using log4net;) and use the ILog interface to get a logger instance.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Logging
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        log4net.ILog log;

        private void Form1_Load(object sender, EventArgs e)
        {
            //Load config
            log4net.Config.XmlConfigurator.Configure();
            log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Logging information
            log.Info("Your data has been successfully saved.");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            int x = 0;
            try
            {
                int y = 1 / x;
            }
            catch(Exception ex)
            {
                //Logging error
                log.Error(ex.Message, ex);
            }
        }
    }
}

You can use different log levels (Info, Warn, Error, Fatal) depending on the severity of the message.

When you log messages using log4net, it will write them to the configured SQL Server database according to the configuration you provided. You now have log4net integrated into your C# Windows Forms application, and you can start logging messages for debugging and monitoring purposes.

VIDEO TUTORIAL