Log4Net Tutorial in C# .net (How can I show log in a file?)

For logging service my choice is log4net from Apache Software Foundation. It is easy to use, open source and well documented. There are also so many logging services but they are not open source. So it is an easy and best solution for you.

Write Log in Console procedures are given below-

1. Download log4net from http://logging.apache.org/log4net/download.html

2. Open visual studio and create a new console application.

3. Add to the project a reference to the \bin\net\2.0\release\log4net.dll assembly in the log4net distribution.

4. write the main method like this

using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using log4net.Config;

namespace LogPractice
{
  class Program
  {
    void Main(string[] args)
    {
     log4net.Config.BasicConfigurator.Configure();
     log4net.ILog log = log4net.LogManager.GetLogger(Program);
log.Debug("THis is sadi's world!");
     log.Info("How beautyful the console looks like");
     log.Warn("You are great you did this");
     log.Error("Who make you know is the best");
     log.Fatal("sadi the great");
     Console.ReadLine();  // Hold the output
     }
   }
 }

Using Log4net Write log in a file, Procedures are given below-

1. Download log4net from http://logging.apache.org/log4net/download.html

2. Open visual studio and create an application.

3. Add to the project a reference to the \bin\net\2.0\release\log4net.dll assembly in the log4net distribution.

4. Now put this web.config/app.config file in configuration tag.

 <configSections>
   <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
 </configSections>
 <log4net>
 <root>
  <level value="DEBUG" />
  <appender-ref ref="LogFileAppender" />
 </root>
 <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
  <param name="File" value="C:\Try\logger\logger\bin\Debug\log.txt" />
  <param name="AppendToFile" value="true" />
  <rollingStyle value="Size" />
  <maxSizeRollBackups value="10" />
  <maximumFileSize value="10MB" />
  <staticLogFileName value="true" />
  <layout type="log4net.Layout.PatternLayout">
  <param name="ConversionPattern" value="%-5p%d{yyyy-MM-dd hh:mm:ss} – %m%n" />
  </layout>
 </appender>
 </log4net>

this configuration creates a log file in C:\temp\log.txt.

5. To use log4net put this as a local class variable:   protected static readonly ILog log =
LogManager.GetLogger(Program);

6.    And do this to write messages in the log file.   log.Debug(“this text will be in log file”);

For Example:

using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using log4net.Config;

namespace <code>LogPractice</code>
{
 class Program
 {
 protected static readonly ILog log = LogManager.GetLogger(typeof(Program));
 static void Main(string[] args)
 {

 log4net.Config.XmlConfigurator.Configure();
 //————————–
 log.Warn("sadi the great");
 }
 }
}

7. Compile and run the application, and you’ll see output to the console

N.B : if you run this code log will show in the c:/temp/log.txt file.

112 thoughts on “Log4Net Tutorial in C# .net (How can I show log in a file?)

  1. You are awesome. I read same kind of articles in as many as 7 websites.

    I felt something different when i went thru ur webpage. Ah! I was right I got the log4net working… cool

  2. There are millions of examples of how to use log4net with a file appended. Why can you not give an example of how to log with a database?

  3. Thanks, and I have a question –> My app need to write 2 log files, one for success message, one for failure message, what should I do?
    And idea?

    • Hi james,

      Sorry for being late reply. I think you can solve this problem by creating a log service that can help you in a very sophisticated way. You can also use log4net and use the log level. You can show your success message by info and failure message by error level then you need not to create another log file.

      Thanks!

    • Hopefully you’ve solved your problem by now but there is a fairly simple way to solve this problem by using two separate loggers.

      Instead of just having one “ILog log = LogManager.GetLogger(typeof(Program));” statement you could just have a successLog and a failLog:

      ILog successLog = LogManager.GetLogger(typeof(Program)+”.Success”);

      (fit to whatever your logger naming scheme is)

      Seems too easy to forget that you can easily have multiple loggers within a single class just because you get used to having a single static logger defined per class.

  4. I am new to Log4Net and have visited so many sites to find step by step tutorial to understand it and make it working but was disappointed. When I read your article and tries to implement LOG4NET it worked. Thanks a lot.

  5. Didn’t work. I got a “Missing Attribute value on ‘ref’. And 26 “Could not find scheme information for the element ‘…'” I am using Visual Studio 2010 Beta 2.

  6. Sorry, I fixed my last problem. I didn’t add using log4net.Config. Now, the file does not create. I am running Windows 7. Maybe something wrong with permissions?

  7. I tried to write an log.Info(“…”); to a log.txt, but the file is not even created. I am running Windows 7. So maybe file permissions are an issue? Some help would be appreciated.

  8. Hi Sadi,
    I have an application which is using 5 threads and all are running simultaneously. I need to write into a single log file whenever any of the thread is failing and also it should write into log file once the thread is completed successfully. Do you have any example programs for this?

    • I think you can use log4net for doing this. Log4net has the flexibility to doing this.
      unfortunately I have not written down any program which can help you in this matter.
      In My solution(Program) I have used my built in logging service. This is not very hard to build.

  9. Great way of explaining things. However, I am not technical savvy and am in a dire need of some help. I would appreciate if you could provide some assistance/ guidance

    We are looking into setting up a custom messaging alert system (business and system related messages) to be logged in a custom Oracle table (to be created) and forward those automatically with an option of sending them via email, IM, or text. These messages might come from web or client based applications. Once alert message is created and sent we would like to use the same oracle table and build some kind of dashboard (web or client)

    I would appreciate any help in this regard.

    Thank you

    Roan

  10. I am getting the following 2 errors when trying to compile:

    log4Net.Config.XmlConfigurator.Configure();
    The name ‘log4Net’ does not exist in the current context

    protected static readonly ILog log = LogManager.GetLogger(typeof(Program));
    The type or namespace name ‘Program’ could not be found (are you missing a using directive or an assembly reference?)

    Can you help?

    • Hey, Program is the class name. Your class name is Program?
      You can also use the below statement:-

      private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

      This will automatically point to current class.

    • Late, but still useful for others:

      In the binary file you download from log4net page, it also appears a “net-cp” folder… Those files are designed for Client Profile projects (which may be yours). That will just do. Good luck!

  11. One doubt ?

    What ever method of getlogger object we are using will go to log file ?

    I mean all the below strings are will write into the log file ?

    log.Debug(“THis is sadi’s world!”);

    log.Info(“How beautyful the console looks like”);

    log.Warn(“You are great you did this”);

    log.Error(“Who make you know is the best”);

    log.Fatal(“sadi the great”);

    Or any difference is in this method ? (Like log.Error can be used only when error is throwing ..etc..)

    Please clarify ?

    • Hi Menon,
      These 5 types are used to identify the type of error occurred in your application just by seeing the log file. You can use appropriate methods whereever you feel that is required.
      The log will have the error type as prefix (eg. Debug or Warn)

      Also you can restrict the type of error to be logged by using the below tag inside the Root tag.

      ErrorTypes can be:
      “All” — All the errors will be logged
      “Debug” — From Debug to Fatal (same as like “All”)
      “Info” — From Info to Fatal (except Debug)
      “Warn” — From Warn to Fatal (except Debug and Info)
      “Error” — Only Error and Fatal
      “Fatal” — Only Fatal errors will be logged.

  12. Great example, thanks.

    Question: For an asp.net app, do I need to put

        log4net.Config.XmlConfigurator.Configure();

    in every Page_Load?
    Is it possible to execute this once for the whole app?

  13. I faced several issues with this simple task. I had to use XmlConfigurator to get it working instead of BasicConfigurator as BasicConfigurator is obsolete. Version of log4net is 1.2.10.0.

  14. Sadi,

    I am new to logging and trying to use log4net in the wpf web browser application to write log in a file. I dont get an error message but log file is not generated.

    Thanks in advance for your help.

  15. Hi,
    I m creating an application in MVC, I m new to log4net, i want to create a log of what actions are slowing us down for the whole site and let those events build up for 2-3 days. Then group by action, and get an average time to process, and see what the major issues are in the application. and i have no idea how to achieve this, will u please help me on this. I have implemented you code in my app and it is creating log file successfully, but i m not sure how to find out the exact time taken by each event/action.

    Please reply soon….

  16. Thanks for the example and q&a. They are great help for me to implement the log in my application.
    I faced two problems:
    1. There are some message that we want to put into log no matter what level it is. Is there a way to do it?
    2. Our application allows user to change log evel during runtime. Therefore, we add the log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(SpecialDirectories.OptionsDotConfig)) if there is any change in the log level. But it creates new log file everytime. Is it possible to keep writing to the same log file?

    Best Regards,
    SJC

  17. Hi!!! i am doing what you said but when I execute this line:
    log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(“app.config”));
    I get this error:

    Value cannot be null.
    Parameter name: address

    and I get it too if I use the AssemblyInfo.

    my app.config file is:

    thank you!!!!!!!!

  18. Hi,

    Won’t mind if someone gives me a quick tip on how to configure log4net to log INFO to FileSystem (only) and ERROR & FATAL to File, DB and Email.

    At the moment, I set threshold value to ERROR for my AdoNetAppender & SmtpAppender, INFO to my LogFileAppender and no level value to my . It sends both INFO to my FileSystem and DB and sends ERROR to all 3. I want to prevent INFO from going into the DB.

    Thanks.

  19. For some reason, Line 6 of my prev post didn’t come out properly. It should read

    .. SmtpAppender, INFO to my LogFileAppender and no level value to my root. It sends both …

  20. Hi Sadi,

    can I have multiple log file running for an application as it is required to log error and success parameters in different files

    can you please tel me the configuration for this?

  21. Hi, Nice article. Unfortunately I dont have Visual Studio. Can you please advice how can I load the dll in aspx.cs file. Any pointer will be helpful.

    regards

  22. Hi,

    I’ve written below line of code:

    log4net.Config.XmlConfigurator.Configure(configFile);
    log4net.Appender.IAppender[] aps = log4net.LogManager.GetRepository().GetAppenders();

    but aps.count is returning as “0”. I have added following code in a seperate app.config file:

  23. This is excellent………… but i want to read the app.xml file into a dataset and i want to show this in a gridview. Is this possible? If possible please let me know the example.

  24. This is excellent………… but i want to read the app.xml file into a dataset and i want to show this in a gridview. Is this possible? If possible please let me know the example.

  25. If you’re working with Visual Studio 2010 default setup you’ll probably get the error: The name ‘log4Net’ does not exist in the current context.
    The reason is that your target framework is “.Net Framework 4 Client profile”.
    Right click your project -> properties ->change target framework to “.Net Framework 4”

    Good luck
    Fred

    • Hey Fred – I spent a whole day tearing my hair out trying to get log4net working with VS2010. I just tried you suggestion and it works !!

      Excellent -I have absolutely no idea why it works but it does.

      Inner harmony is now restored – Many many thanks

      Bob

  26. Pingback: links for 2011-02-24 - Craig's Blog

  27. Hi..
    I tried your example.I think keping configuration information in separate xml is more beneficial rather than in app/web.config.Earlier i got problem while logging in release mode while it was working file in debug mode.
    Keeping it separate helped me.
    Thanks again

  28. Nice Article…

    After uninstall (web application) log folder not removed. This folder have empty log file. What should I do to remove this log file?

  29. Pingback: log4net – write log in a file « Vijay Mahankali

  30. Hi,
    I am using log4net, how can i fix/restrict the log file size by removing old log.It would be nice if i could take backup of these files.

    thanks

  31. the logging to file part doesn’t seem to work for me… does anybody else get this:

    Could not find schema information for the element ‘log4net’.
    Could not find schema information for the element ‘root’.
    Could not find schema information for the element ‘level’.
    ..
    ..

    The program runs, it just seems to do nothing.

  32. Hello,
    I followed the example for a console application but i get this error:
    The type initializer for ‘XXXXX’ threw an exception.
    Any ideas what could I be doing wrong?
    Thanks!

  33. 5. To use log4net put this as a local class variable: protected static readonly ILog log =
    LogManager.GetLogger(Program);

    should be
    (typeof(Program)) instead of (Program)

  34. Good article.

    but I found the log.txt is not created, untill I change the configure line to be
    log4net.Config.DOMConfigurator.Configure();

    Can you explain the difference between them?

    Thanks in advance!

  35. Hi,

    I am using above logging method as it was working fine till I was debugging. When I finally made the application as Windows Service, the program itself is working as its performs what is should do, but it is not logging anything…..

    I have added the assembly line as mentioned on different websites.
    Regards
    Hassan

  36. Pingback: Exception Handling in ASP.NET MVC 3– Follow up « KK's bytes

  37. Hi, the file will not create after I publish my console app. It works perfect on dev server. I can’t even get the trace file to work.. I’m using Windows 7, have given IIS_WPG full access to folder and have tried to set the
    Any ideas?
    Thanks

  38. I used to be recommended this blog through my cousin. I’m now not positive whether this post is written by way of him as no one else recognise such specified about my trouble. You are wonderful! Thanks!

  39. i am using Log4net.ddl in the web serivce to get log,but i can able to get log on the location below my code: in wwb config:

    …..
    ……..
    ……..

    in c.s page:

    class Logger
    {
    private static ILog _log = LogManager.GetLogger(typeof(Logger));
    ……

    static Logger()
    {
    ReInitialise();

    }
    public static void ReInitialise()
    {
    LogManager.ShutdownRepository();
    LogManager.ResetConfiguration();

    try
    {
    log4net.Config.XmlConfigurator.Configure();
    }

    but i am not getting the log file..

  40. Hi,

    I need to create a logfile for my application. So I am following your way of approach.
    But I am not stuck in mind as not able to find log4net.dll in downlaoded folder to add the reference.

  41. I have two appenders in my app.config for a .net C# application. One is for a database log and the other for a rolling file appender. I need to use these two appenders but with a different message parameter to each one. I therefore cannot just use one log.info call but I need to instantiate two ILog objects, each one connected to a different appender from my app.config. Is this possible?

    Thanks for any help you can offer.

  42. Why log4net has ALL and DEBUG, as they both do the same thing? There should some reason they created two levels with same functionality.
    Appreciate the reply.

  43. Hi,

    I’m stuck @ Using Log4net Write log in a file.
    I made a the app.config file (add,new item,application configuration file) and copied your code in it, now it gives me 3 errors:
    1.)XML document cannot contain multiple root level elements.
    2.)The “log4net” element is not declared
    3.) Application Configuration file “App.config” is invalid. There are multiple root elements. Line 4, position 2.

    Also “Write Log in Console” did not work for me:
    Program ‘D:\Visual Studio 2010\Projects\O2PROG\Logger\obj\x86\Debug\Logger.exe’ does not contain a static ‘Main’ method suitable for an entry point Logger

    Copied exact code:
    using System;
    using System.Collections.Generic;
    using System.Text;
    using log4net;
    using log4net.Config;

    namespace LogPractice
    {
    class Program
    {
    void Main(string[] args)
    {
    log4net.Config.BasicConfigurator.Configure();
    log4net.ILog log = LogManager.GetLogger(typeof(Program));
    log.Debug(“THis is sadi’s world!”);
    log.Info(“How beautyful the console looks like”);
    log.Warn(“You are great you did this”);
    log.Error(“Who make you know is the best”);
    log.Fatal(“sadi the great”);
    Console.ReadLine(); // Hold the output
    }
    }
    }

    Greets,
    Dubzzz

  44. Great tutorial. Just one following correction:

    log =
    LogManager.GetLogger(Program);

    should be
    (typeof(Program)) instead of (Program)

  45. Hi! Generally we are not interested to show any type of application error to end user. Error logs are very important for collecting all error data generated by an application. It is more useful during an early or beta release of a product. That’s why it is better to store any kind of exceptions in one place. This files can be send by email or others technology to developer. Time to time developer must analyze them and fix all the bugs without knowing clients. It will increase application performance. So thanks for sharing your knowledge.

  46. This is a good tip particularly to those fresh to the blogosphere. Short but very accurate info… Appreciate your sharing this one. A must read article!

  47. Good Blog It solved my Problem. I have one Issue How to Login User ID through the Log4Net ….Is there any way?

  48. I like the helpful info you supply on your articles. I’ll bookmark your blog and take a look at again right here regularly. I am fairly sure I’ll be told a lot of new stuff proper right here! Good luck for the next!

  49. Needed to post you that little bit of note to finally say thank you the moment again for the pleasing guidelines you have provided here. This is so remarkably generous with you to deliver publicly what exactly some people could possibly have advertised as an electronic book to make some money on their own, most notably considering that you might well have tried it in case you considered necessary. The thoughts also acted to be a easy way to be aware that most people have a similar zeal just as my very own to learn more and more in regard to this problem. I am certain there are thousands of more pleasant situations up front for people who find out your site.

  50. How to create the common library(dll) for Error logging using log4net. That dll will be implemented may application

Leave a reply to freeman Cancel reply