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.

About these ads

About Md Shaik Sadi

I am Md. Shaik Sadi, got my B.Sc.(Engg) degree in Computer Science and Engineering and started my carrer as a trainee developer. I have worked on different phases of software development life cycle. Recently, I am working on asp.net/2 and want to stablish my career on this platfrom.
This entry was posted in Computer Science and tagged , , , . Bookmark the permalink.

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

  1. Prabhakar Kasi says:

    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. Himanshu says:

    Your way of telling about how to use log 4net is really awesome…

    i visited more than 10 pages about how to use log4net but your page did the trick….

  3. Lee says:

    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?

  4. Md. Shaik Sadi says:

    thanks for ur comment Lee. I was little bit busy with my task.But i posted how to store log in database using log4net.

    you can view my new post

    http://sadi02.wordpress.com/2008/09/15/how-to-store-log-in-database-using-log4net/

    cheers

  5. James Yeh says:

    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?

    • Md. Shaik Sadi says:

      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!

    • Nick V says:

      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.

  6. Benjy says:

    Nice work. Found this after a long search and numerous other examples that did not work.

    cheers

  7. Muhammad Asif says:

    Excellent Tutotial about log4net!

  8. Arunkumar says:

    Good.I feel that this is easy understandable and work fine and good example.Keep it up.

  9. Manjeet says:

    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.

  10. jignesh says:

    hey it’s great……….i done with help of you websit….

  11. MichaelL says:

    Your article didn’t work, I got errors…

  12. Md. Shaik Sadi says:

    Send the error
    if I can help you in any way ..

    -Author

  13. vinov says:

    Excellent article! just started using directly.
    thanks a lot.

    Vinov

  14. Nazish Kanwal says:

    Very simple and nice article for quick start.

  15. Jack says:

    how can i change the file location in code? does log4net support it?

  16. Foyzul Karim says:

    Man..you are great…it helped me a lot…

  17. yang says:

    thanks nice and simple

  18. Mohit Deshpande says:

    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.

  19. Mohit Deshpande says:

    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?

  20. Mohit Deshpande says:

    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.

  21. ShweNanThu says:

    I’ll test it.Thanks u.

  22. Sivakumar says:

    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?

    • Md. Shaik Sadi says:

      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.

  23. Ron says:

    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

  24. James says:

    Thanks.. really useful…

  25. Lynn says:

    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?

    • Sivakumar says:

      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.

    • Francisco Bouza says:

      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!

  26. as says:

    saddasadsdasas

  27. NK Menon says:

    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 ?

    • Sivakumar says:

      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.

  28. Sivakumar says:

    [level value="ALL" /]

  29. Scott says:

    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?

  30. Rajesh says:

    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.

  31. Ryan says:

    Thanks for the example. Its helping me get started :).

  32. Ravi says:

    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.

  33. Anil D says:

    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….

  34. SJC says:

    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

  35. Nicole says:

    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!!!!!!!!

  36. Robert says:

    Excellent tutorial. Got me up and running. I was struggling the official log4net documentation! Good job!

  37. Kwex says:

    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.

  38. Kwex says:

    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 …

  39. Ahmed says:

    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?

  40. Vijay Srivastava says:

    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

  41. Sima Agrawal says:

    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:

  42. kapil says:

    I saw a lot of examples, but urs one realy works.- Thanks

  43. Satya says:

    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.

  44. Satish says:

    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.

  45. Fred Verbeke says:

    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

    • Bob W says:

      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

    • freeman says:

      thanks, worked :D

    • Dennis says:

      Hi,

      Fred Verbeke, I was also expericing this error when compiling my solution.

      Your suggestion fixed my problem!

      Cheers

  46. Anup says:

    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

  47. Dennis says:

    I did as is above and I am getting the following error;
    Unrecognized configuration section log4net

  48. Adam says:

    @Fred Verbeke

    Thanks! That just tripped me up for 30 minutes.

  49. Vijay says:

    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?

  50. Yaniv says:

    Great article ! first time i got it to work :P thanks :P

  51. keith says:

    hey i am new to .net. i want to write a code that will create logfile on daily basis. how do i do that??

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

  53. basim says:

    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

  54. basim says:

    by fix i mean limit the size of log file

  55. James says:

    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.

  56. christos says:

    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!

  57. Keke says:

    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)

  58. Jimmy Abu Al Denien says:

    Good job man.
    Thanks for sharing this example.

    ~Jimmy.

  59. dylanwind says:

    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!

  60. Hassan Shaikh says:

    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

  61. thx says:

    thx. helped me too :)

  62. One line of code is worth thousand lines of explaination.
    Thanks a lot,
    Jay

  63. Very cool and without any redundant comments and analysis. Code speaks for itself! :)

  64. BrianS says:

    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

  65. 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!

  66. maran says:

    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..

  67. bvc.here@gmail.com says:

    This really helped me get started without any issue..thanks a bunch, Sadi!

  68. bhavya says:

    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.

  69. Nissim levy says:

    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.

  70. scorpion says:

    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.

  71. Dubzzz says:

    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

  72. Thank you, I’v been compiling different guides and tutorials, yours made the final touch.
    I appreciate the effort.

  73. Caner Çelik says:

    Such a nice work!
    But, many people faced similar problems as you see.
    Could you update your article for the current version of log4net?

  74. tonda says:

    I follow up the log4net settings by doing copy/paste then i have a error message it’s not well configured.

  75. A_Halim says:

    Great tutorial. Just one following correction:

    log =
    LogManager.GetLogger(Program);

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

  76. Hugh Jackman says:

    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.

  77. Anonymous says:

    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!

  78. Ambarish BH says:

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s