2

I have a Windows Forms App, and I am trying to implement log4net so that I can write some logs. However I cannot seem to get it to work.

My implementation is as follows :-

log4Net.config :-

<configuration>
<!-- Register a section handler for the log4net section -->
    <configSections>
        <section name="log4net" type="System.Configuration.IgnoreSectionHandler" requirePermission="false" />
    </configSections>
    <appSettings>
        <!-- To enable internal log4net logging specify the following appSettings key -->
        <add key="log4net.Internal.Debug" value="true"/> 
    </appSettings>
    <!-- This section contains the log4net configuration settings -->
    <log4net>
        <!-- Define some output appenders -->
        <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
            <file value="C:\Johann\Log\rolling-log.txt" />
            <appendToFile value="true" />
            <maxSizeRollBackups value="10" />
            <maximumFileSize value="100" />
            <rollingStyle value="Size" />
            <staticLogFileName value="true" />
            <layout type="log4net.Layout.PatternLayout">
                <header value="[Header]&#13;&#10;" />
                <footer value="[Footer]&#13;&#10;" />
                <conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message%newline" />
            </layout>
        </appender>
        <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
            <file value="C:\Johann\Log\log-file.txt" />
            <appendToFile value="true" />
            <!-- An alternate output encoding can be specified -->
            <!-- <encoding value="unicodeFFFE" /> -->
            <layout type="log4net.Layout.PatternLayout">
                <header value="[Header]&#13;&#10;" />
                <footer value="[Footer]&#13;&#10;" />
                <conversionPattern value="%date [%thread] %-5level %logger [%ndc] &lt;%property{auth}&gt; - %message%newline" />
            </layout>
        </appender>

        <!-- Setup the root category, add the appenders and set the default level -->
        <root>
            <level value="ALL" />
            <appender-ref ref="LogFileAppender" />
            <appender-ref ref="RollingLogFileAppender" />
        </root>
    </log4net>
</configuration>

and in my .cs

using log4net;

[assembly: log4net.Config.XmlConfigurator(Watch = true)]
[assembly: log4net.Config.Repository()]

public partial class Form1 : Form
{

    public static readonly ILog log = LogManager.GetLogger("NotifMailer");


    private void button1_Click(object sender, EventArgs e)
    {

        //CreateFolder();

        log4net.Config.BasicConfigurator.Configure();

        if (log.IsErrorEnabled)
        {
            try
            {
                log.Error("Page Load failed : ");
            }
            catch (Exception exc)
            {
                string exception = exc.Message;
            }
        }

        if (log.IsDebugEnabled)
        {
            try
            {
                log.Debug("Application loaded successfully.");
            }
            catch (Exception exc)
            {
                string exception = exc.Message;
            }
        }
    }
}

As you can see from this code, I did a small test to create a file and folder through code " //CreateFolder(); " and that works, so its not an issue with permissions.

What I am doing wrong?

Thanks for your help and time

UPDATE

Log4Net.config :-

<configuration>
    <configSections>
            <section name="log4net" type="System.Configuration.IgnoreSectionHandler" requirePermission="false" />
    </configSections>
    <log4net>
        <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
            <file value="C:\Johann\Log\rolling-log.txt" />
            <appendToFile value="true" />
            <maxSizeRollBackups value="10" />
            <maximumFileSize value="100" />
            <rollingStyle value="Size" />
            <staticLogFileName value="true" />
            <layout type="log4net.Layout.PatternLayout">
                <header value="[Header]&#13;&#10;" />
                <footer value="[Footer]&#13;&#10;" />
                <conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message%newline" />
            </layout>
        </appender>
        <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
            <file value="C:\Johann\Log\log-file.txt" />
            <appendToFile value="true" />
            <layout type="log4net.Layout.PatternLayout">
                <header value="[Header]&#13;&#10;" />
                <footer value="[Footer]&#13;&#10;" />
                <conversionPattern value="%date [%thread] %-5level %logger [%ndc] &lt;%property{auth}&gt; - %message%newline" />
            </layout>
        </appender>

        <root>
            <level value="ALL" />
            <appender-ref ref="LogFileAppender" />
            <appender-ref ref="RollingLogFileAppender" />
        </root>
    </log4net>
</configuration>

App.Config :-

<appSettings>
    <add key="log4net-config-file" value="Log4Net.config"/>
</appSettings>

Assembly.cs :-

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)] 

Form1.cs :-

private static readonly ILog log = LogManager.GetLogger(typeof(Form1));

private void button1_Click(object sender, EventArgs e)
{

    //log4net.Config.BasicConfigurator.Configure();

    XmlConfigurator.Configure(new FileInfo(ConfigurationManager.AppSettings["log4net-config-file"]));

    log.Error("Page Load failed : ");
    log.Debug("Application loaded successfully.");

}

Still no luck though

Bronumski
  • 14,009
  • 6
  • 49
  • 77
JMon
  • 3,387
  • 16
  • 63
  • 102

3 Answers3

2

I don't normally wire up log4net using the assembly attribute

If you are using a configuration file external to the app/web.confg your root element should be:

<?xml version="1.0"?>
<log4net>
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="C:\Johann\Log\rolling-log.txt" />
      <appendToFile value="true" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="100" />
      <rollingStyle value="Size" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <header value="[Header]&#13;&#10;" />
        <footer value="[Footer]&#13;&#10;" />
        <conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message%newline" />
      </layout>
    </appender>
    <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
      <file value="C:\Johann\Log\log-file.txt" />
      <appendToFile value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <header value="[Header]&#13;&#10;" />
        <footer value="[Footer]&#13;&#10;" />
        <conversionPattern value="%date [%thread] %-5level %logger [%ndc] &lt;%property{auth}&gt; - %message%newline" />
      </layout>
    </appender>

    <root>
      <level value="ALL" />
      <appender-ref ref="LogFileAppender" />
      <appender-ref ref="RollingLogFileAppender" />
    </root>
</log4net>

According to the docs:

If neither of the ConfigFile or ConfigFileExtension properties are specified, the application configuration file (e.g. TestApp.exe.config) will be used as the log4net configuration file.

So you will either need to do:

[assembly: log4net.Config.XmlConfigurator(ConfigFile="log4net.config",Watch=true)]

Or rename the log4net.config to YourApp.exe.log4net and set the assembly attribute to:

[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension="log4net",Watch=true)]

Or remove the attribute all together and use the XmlConfigurator:

XmlConfigurator.ConfigureAndWatch("log4net.config");

http://logging.apache.org/log4net/release/manual/configuration.html

Bronumski
  • 14,009
  • 6
  • 49
  • 77
  • I have already tried that in the Assembly :(( [assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)] – JMon Feb 28 '12 at 12:43
  • Hi Bronumski what does your root have different from my root? For me they look similar – JMon Feb 28 '12 at 12:50
  • @Johann In an external file it should be "log4net" not "configuration" – Bronumski Feb 28 '12 at 12:52
  • @Johann could you update the question to include the full content of the log4net.config file? – Bronumski Feb 28 '12 at 12:54
  • @Johann you also need to include either the name of the config file or the extension. See my updated answer. – Bronumski Feb 28 '12 at 12:57
  • ok Updated but its not very clear, some parts of the code are not visible :( – JMon Feb 28 '12 at 13:01
  • tried your approaches Bronumski, nothing works though. at the moment I ahve the implementation I have in the UPDATE – JMon Feb 28 '12 at 13:09
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/8305/discussion-between-bronumski-and-johann) – Bronumski Feb 28 '12 at 13:13
  • tried the chat but there is some firewall i guess, am at work – JMon Feb 28 '12 at 13:24
  • @Johann I have updated the answer using the xml you have given me. If you are using an external log4net file you need to remove the other bits that would be in an app.config. Remove everything except the log4net element and its contents. – Bronumski Feb 28 '12 at 13:30
  • Ok updated with your updated XML config file, no luck though. So now I have your config file, the App.Config which has
    – JMon Feb 28 '12 at 13:40
  • @Johann you dont need the section element, just cut and paste what is in my answer straight into your xml config file, there should be nothing else – Bronumski Feb 28 '12 at 14:00
  • Bronumski, I did, but did not work. its really mysterious. I have started fresh, but still no luck – JMon Feb 28 '12 at 14:02
  • @Johann Good, can you share it? – Bronumski Feb 28 '12 at 14:40
  • I did in the answer. Basically everything is the same, just moving XMLConfigurator.Configure in the Initializing code, before you actually create the Log file. – JMon Feb 28 '12 at 14:58
1

found my problem.

I should have done

XmlConfigurator.Configure();

inside Program.cs, since it has to run that piece of code before doing the initialize of the logger

private static readonly ILog log = LogManager.GetLogger(typeof(Form1));
JMon
  • 3,387
  • 16
  • 63
  • 102
0

log4net.Config.BasicConfigurator.Configure();

This is a bare-bones configuration which only supports writing to the Console and also ignores your config file.

You should be using an XmlConfigurator rather than BasicConfigurator

sgmoore
  • 15,694
  • 5
  • 43
  • 67
  • I have removed the BasicConfigurator and did the XmlConfigurator still no luck though //log4net.Config.BasicConfigurator.Configure(); log4net.Config.XmlConfigurator.Configure(); – JMon Feb 28 '12 at 12:48