41

I have some troubles while writing logs from log4net to the file. I seem to do all as described in manual, but that does not work. Here is my logging.config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net>
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="log.txt" />
      <appendToFile value="true" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %message%newline" />
      </layout>
    </appender>
  </log4net>
</configuration>

Please help with an example of configuration file which actually works.

Philipp M
  • 1,877
  • 7
  • 27
  • 38
Yury Pogrebnyak
  • 4,093
  • 9
  • 45
  • 78
  • 2
    Are you Configuring the Xml setting... http://logging.apache.org/log4net/release/sdk/log4net.Config.XmlConfigurator.Configure_overload_5.html – Lloyd Mar 21 '12 at 13:14

5 Answers5

84

Here is a complete step-by-step guide to adding Log4Net to your project, under Visual Studio 2012 and .NET 4.5.

  1. Add a new C# console app to your solution.

  2. Select Tools >> Library Package Manager >> Manage NuGet Packages For Solution and search for log4net. Install it, and select which project(s) you want to add the log4net references. enter image description here

  3. Edit Program.cs:

using System;
namespace Log4Net
{    
    class Program
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger
                (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        static void Main(string[] args)
        {
            Console.WriteLine("Writing to \"log.txt\" in the same directory as the .exe file.\n");
            log.Info("Info logging");
            try
            {
                throw new Exception("Exception!");
            }
            catch (Exception e)
            {
                log.Error("This is my error", e);
            }
            Console.WriteLine("[any key to exit]");
            Console.ReadKey();
            }
        }
    }
}
  1. Add log4.config, right click and select Properties then select Copy to Output Directory - Copy If Newer.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>

  <log4net>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="log.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="250KB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>
    <root>
      <level value="ALL" />
      <appender-ref ref="RollingFileAppender" />
    </root>
  </log4net>
</configuration>
  1. Edit App.Config so it matches the following:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <appSettings>
        <add key="log4net.Config" value="log4.config"/>
        <add key="log4net.Config.Watch" value="True"/>
        <add key="log4net.Internal.Debug" value="False"/>
    </appSettings>
</configuration>
  1. Run the program and observe the file log.txt that is created in the output \bin\Debug\ directory:

    2013-08-10 11:54:26,798 [10] INFO  Log4Net.Program [(null)] - Info logging
    2013-08-10 11:54:26,824 [10] ERROR Log4Net.Program [(null)] - This is my error
    System.Exception: Exception!
       at Log4Net.Program.Main(String[] args) in C:\Test\Log4Net\Program.cs:line 14
    
  2. In the future, if you want to add log4net to another Project, select Tools >> Library Package Manager >> Manage NuGet Packages For Solution select log4net and click Manage then tick the Projects you want to add log4net to. enter image description here

ahsteele
  • 26,243
  • 28
  • 134
  • 248
Contango
  • 76,540
  • 58
  • 260
  • 305
  • Just a note on the configSections: "If this element is in a configuration file, it must be the first child element of the element." https://msdn.microsoft.com/en-us/library/aa903350(v=vs.71).aspx – unicorn2 Jun 27 '17 at 07:01
  • could you elaborate on the roll the App.config settings play? – jxramos Dec 12 '17 at 19:32
  • @jxramos Settings in app.config control everything to do with logging, including whether it writes to a file, what format each line is, if it writes to the console, etc. It's probably easier to look at the log4net docs for all of the options. – Contango Dec 14 '17 at 16:42
47

You don't seem to have a <root> element that references your appender:

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

    <log4net>
      <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
        <file value="log.txt" />
        <appendToFile value="true" />
        <rollingStyle value="Size" />
        <maxSizeRollBackups value="10" />
        <maximumFileSize value="250KB" />
        <staticLogFileName value="true" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
        </layout>
      </appender>
      <root>
        <level value="INFO" />
        <appender-ref ref="RollingFileAppender" />
      </root>
    </log4net>
</configuration>
Philipp M
  • 1,877
  • 7
  • 27
  • 38
jlew
  • 10,491
  • 1
  • 35
  • 58
21

Did you call the configure method when the application starts for the first time ?

log4net.Config.XmlConfigurator.Configure();

If yes. You should be good. Check the file permissions on the disk you are writing.

If you want you can enable log4net internal debugging also to figure out what is wrong.

http://logging.apache.org/log4net/release/faq.html#troubleshooting

Shyju
  • 214,206
  • 104
  • 411
  • 497
  • you could also enable log4net internal debugging, as detailed here: http://logging.apache.org/log4net/release/faq.html#troubleshooting – paul Mar 21 '12 at 13:15
  • For an .NET web app, does this line only need to be called once? i.e. in the Application_Start() of the Global.asax file? Or on each users session start i.e. Session_Start() ? – Seany84 Mar 21 '12 at 13:17
  • @paul : Added that to my answer. Thanks Paul – Shyju Mar 21 '12 at 13:18
  • 1
    @Seany84 : Not for each session. Only once when the application starts. thats y we put this in the Application_start event in global.asax which will fire only once in the application life time. – Shyju Mar 21 '12 at 13:19
  • @Shyju Thanks for clearing that up for me. I recently introduced log4net into a commercial application and I am going to have to move this Configure() to the Application_Start(). Thanks for the advice. – Seany84 Mar 21 '12 at 13:22
6

There are two things that you can do:

One, if you want to use a seperate config file, by adding the following to you app.config file it will configure logging automatically.

<?xml version="1.0"?>
<configuration>
    <appSettings>
        <add key="log4net.Config" value="log4.config"/>
        <add key="log4net.Config.Watch" value="True"/>
        <add key="log4net.Internal.Debug" value="False"/>
    </appSettings>
</configuration>

Otherwise, you need to initiate logging in the start of your application.

//Initiate logging based on web.config file
log4net.Config.XmlConfigurator.Configure();

// Create a logger for use in this class
log4net.ILog log4 = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
Kevin Green
  • 1,137
  • 11
  • 21
3

Fantastic. The answers are correct... except that they weren't working for me

Searched the net and finally discovered I was missing the following line in Assembly.cs:

[assembly: log4net.Config.XmlConfigurator]
JAnton
  • 1,095
  • 8
  • 16