Click here to Skip to main content
13,662,176 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

77.7K views
2.6K downloads
32 bookmarked
Posted 20 Jun 2016
Licenced CPOL

Perfect Log4Net with C#

, 20 Jun 2016
Rate this:
Please Sign up or sign in to vote.
Don't know how to store the logging message into a text file? Let's get started with Log4Net in this tutorial.

Introduction

Nowadays, most applications use logging as a way to store information about performed operations, because those data are very useful when you have to diagnose issues while running your apps. We have many ways to store the log into database, textfile, etc. Instead of using complex ways, go ahead to use an easier to use and existing open source library such as log4net. It's a common library, very powerful and the most important is very easy to use.

Should Know Before Starting

  • Application demo: Console app
  • Log4Net version: 2.0.5
  • Visual Studio: 2015

There are 5 log message levels:

  • FATAL
  • ERROR
  • WARN
  • INFO
  • DEBUG

You will also be able to find the video link here: Perfect Log4Net with C#

Integration Steps

Follows the steps to do the integration between Log4Net and C# Console application as example:

Step 1

Open your Visual Studio instance on your PC.

Step 2

Create a console project.

Step 3

Add log4net refer to your project. We have 2 ways for adding that library. The first one is download the log4net from the internet to your local device, then add the reference to DLL file. The second one is download it from Nuget. I preferred this way by the following:

  • Right clicks on your project
  • Click Manage NuGet Packages…
  • Clicks on Browse on the left hand
  • Type log4net in search box under Browse option
  • Select log4net package and click Install

Step 4

Open AssemblyInfo.cs file under Properties, then add the below line of code under the [assembly: AssemblyCulture("")] line.

// Let log4net know that it can look for configuration in the default application config file
[assembly: log4net.Config.XmlConfigurator(Watch = true)] 

Step 5

Open the App.config file, by default after creating the console app, it will contain the following code:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" 

    sku=".NETFramework,Version=v4.5.2" />
  </startup>  
</configuration>

Next, add the configuration code for log4net into this file, but don't forget to add those configurations before <startup> </startup> tag to make sure the log4net runs well. After that, it should be:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" 

    type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
  </configSections>

  <log4net>
    <appender name="TestAppender" 

    type="log4net.Appender.RollingFileAppender" >
      <file value="E:\log\MyTestAppender.log" />
      <encoding value="utf-8" />
      <appendToFile value="true" />
      <rollingStyle value="Date" />
      <!--<rollingStyle value="Size" />
      <maxSizeRollBackups value="5" />
      <maximumFileSize value="5MB" />
      <staticLogFileName value="true" />-->
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %level [%thread] %type.%method - %message%n" />
      </layout>
    </appender>
    <root>
      <level value="All" />
      <!-- If the following line is not included the log file 
      will not be created even if log4net is configured with this file. -->
      <appender-ref ref="TestAppender" />
    </root>
  </log4net>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  
</configuration>

I'm going to explain a little for the above configured.

This line of code...

<configSections> <section name="log4net" 

type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/> </configSections>

...lets the log4net know that the real configuration is stored in XML node called log4net, where we can setup the output log file, define the output layout for messages and set the roolingstyle for data file, etc.

Step 6

Open the Program.cs file, by default, it contains only the Main(string[] args) method. Go ahead to create a method called ImplementLoggingFuntion, which implements the logging feature using log4net. The full code for Program.cs is as below:

using System;
using log4net;
using System.Threading;

namespace Log4Net.CSharp
{
    class Program
    {
        //Declare an instance for log4net
        private static readonly ILog Log = 
              LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        static void Main(string[] args)
        {
            ImplementLoggingFuntion();
        }

        private static void ImplementLoggingFuntion()
        {
            /* We have 5 levels of log message. Let's test all.
             *  FATAL
                ERROR
                WARN
                INFO
                DEBUG
             */
            var secs = 3;
            Log.Fatal("Start log FATAL...");
            Console.WriteLine("Start log FATAL...");
            Thread.Sleep(TimeSpan.FromSeconds(secs)); // Sleep some secs

            Log.Error("Start log ERROR...");
            Console.WriteLine("Start log ERROR...");
            Thread.Sleep(TimeSpan.FromSeconds(secs)); // Sleep some secs

            Log.Warn("Start log WARN...");
            Console.WriteLine("Start log WARN...");
            Thread.Sleep(TimeSpan.FromSeconds(secs)); // Sleep some secs

            Log.Info("Start log INFO...");
            Console.WriteLine("Start log INFO...");
            Thread.Sleep(TimeSpan.FromSeconds(secs)); // Sleep some secs

            Log.Debug("Start log DEBUG...");
            Console.WriteLine("Start log DEBUG...");
            Thread.Sleep(TimeSpan.FromSeconds(secs)); // Sleep some secs

            Console.WriteLine("Press any key to close the application");
            Console.ReadKey();
        }
    }
}

Points of Interest

  • You can reuse this code for your working purposes
  • Very basic, demonstrates and easy to understand

History

  • 21-June-2016: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

ChienVH
Product Manager
Vietnam Vietnam
Updated LinkedIn: https://vn.linkedin.com/in/chienvh

I am currently working as the position of project manager for a long time. Had to take care a lot of projects at the same times, so I don't have many free times in a day for contributing the articles, tips/tricks on codeproject.
While I was at the previous company sometimes I participated in training courses for new employees, so I have good teaching skills and ability to convey information to others. Meaning in each my post I will try to explain more detail as possible for the junior devs are able to implement/understand what's I have done.

Also, would like to share my responsibilities for current position:

• Coordinate internal resources and third parties/vendors for the flawless execution of projects
• Ensure that all projects are delivered on-time, within scope and within budget
• Assist in the definition of project scope and objectives, involving all relevant stakeholders and ensuring technical feasibility
• Ensure resource availability and allocation
• Develop a detailed project plan to monitor and track progress
• Report and escalate to management as needed
• Perform risk management to minimize project risks
• Establish and maintain relationships with third parties/vendors
• Create and maintain comprehensive project documentation
• Support team members to solve technical issues

Opening and looking forward to finding suitable jobs.

You may also be interested in...

Pro

Comments and Discussions

 
QuestionLog4Net Pin
ViralPatva18-Mar-18 2:35
professionalViralPatva18-Mar-18 2:35 
GeneralMy vote of 5 Pin
BillWoodruff3-Jun-17 5:27
mvpBillWoodruff3-Jun-17 5:27 
QuestionThank you! Pin
Member 1293792713-Mar-17 10:23
memberMember 1293792713-Mar-17 10:23 
QuestionLog4Net config made simple Pin
Conrad Gardner15-Dec-16 9:20
memberConrad Gardner15-Dec-16 9:20 
AnswerRe: Log4Net config made simple Pin
ChienVH21-Dec-16 15:56
memberChienVH21-Dec-16 15:56 
Questionlog4Net C# performance logger - configuration, example Pin
Sandra Basler6-Jul-16 6:58
memberSandra Basler6-Jul-16 6:58 
SuggestionHard Coded File Path ? Pin
Paul_Williams30-Jun-16 23:46
groupPaul_Williams30-Jun-16 23:46 
GeneralRe: Hard Coded File Path ? Pin
ChienVH5-Jul-16 4:31
memberChienVH5-Jul-16 4:31 
GeneralRe: Hard Coded File Path ? Pin
stperm4-Aug-16 4:09
memberstperm4-Aug-16 4:09 
GeneralRe: Hard Coded File Path ? Pin
ChienVH5-Aug-16 3:47
memberChienVH5-Aug-16 3:47 
QuestionIs the configSection explanation correct? Pin
George Swan21-Jun-16 5:47
memberGeorge Swan21-Jun-16 5:47 
AnswerRe: Is the configSection explanation correct? Pin
stperm4-Aug-16 4:01
memberstperm4-Aug-16 4:01 
GeneralRe: Is the configSection explanation correct? Pin
ChienVH5-Aug-16 3:46
memberChienVH5-Aug-16 3:46 
GeneralRe: Is the configSection explanation correct? Pin
stperm5-Aug-16 4:21
memberstperm5-Aug-16 4:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01-2016 | 2.8.180810.1 | Last Updated 21 Jun 2016
Article Copyright 2016 by ChienVH
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid