0

I have followed the log4net tutorial very carefully but the logger failed to save as a txt file and failed to appear in the console. I am expecting the log file to be saved under C:\temp.

Here is my app.config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, Log4net"/>
  </configSections>
  <log4net>
    <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="C:\temp\Logs.txt"/>
      <param name="AppendToFile" value="true"/>
      <rollingStyle value="Size"/>
      <maxSizeRollBackups value="10"/>
      <maximumFileSize value="3MB"/>
      <staticLogFileName value="true"/>
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%date [%thread] %-5level %logger - %message%newline"/>
      </layout>
    </appender>
    <root>
      <level value="Debug"/>
      <appender-ref ref="LogFileAppender"/>
    </root>
  </log4net>
</configuration>

I also included

[assembly: log4net.Config.XmlConfigurator(Watch = true)] in the AssemblyInfo.cs.

I placed my logger in the LoggerView.xaml.cs class. (I am using MVVM design pattern.)

[Export]
[PartCreationPolicy(System.ComponentModel.Composition.CreationPolicy.NonShared)]
public partial class LoggerView : Window
{
    private LoggerViewModel _viewModel;
    protected static readonly ILog log = LogManager.GetLogger(typeof(LoggerView));

    [ImportingConstructor]
    public LoggerView(LoggerViewModel viewModel)
    {
        _viewModel = viewModel;
        this.DataContext = _viewModel;
        InitializeComponent();
    }

    static void Main(string[] args)
    {
        log4net.Config.XmlConfigurator.Configure();
        log.Debug("Debug Statement");
        log.Info("Info");
        log.Error("Error Statement");
        log.Warn("Warning Statement");
        log.Fatal("Fatal Statement");
    }
}

Is there anything that I am missing or doing wrong?

Thank you.

DanCode
  • 525
  • 3
  • 7
  • 25
  • At run time check `LogManager.GetRepository().Configured` to see if log4net has picked up the configuration, and you can also look at `LogManager.GetRepository().ConfigurationMessages.Cast()` for any configuration errors. These may not include permission errors though. – stuartd Jun 24 '15 at 17:14
  • try turning on log4net internal debugging: http://stackoverflow.com/questions/756125/how-to-track-down-log4net-problems – Michael Edenfield Jun 24 '15 at 18:33

2 Answers2

0

Verify that log4net has the correct permissions to write to the folder Regarding logging to the console you need to add the appender in as well see this post for more details How to configure log4net to print to console in debug mode

This is part of a config file which has log4net working correctly:

<log4net>
    <root>
      <level value="ALL" />
      <appender-ref ref="RollingFileAppender" />
      <appender-ref ref="SmtpAppender" />
      <appender-ref ref="AdoNetAppender" />
    </root>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="C:\Logs\EntitlementPermissionManagerService.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="100KB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>
</log4net>
Community
  • 1
  • 1
  • I did add the appender in like that article stated. Do you know how to check if log4net have permission to write to the folder? If it does not have permission, how would I grant it permission? – DanCode Jun 24 '15 at 15:10
  • I have just updated my posting with my config file and your's looks different so compare the two and make the changes. – Sameer Chauhan Jun 24 '15 at 15:13
  • Check this link out for folder access http://stackoverflow.com/questions/4946042/wpf-application-not-getting-file-access-rights – Sameer Chauhan Jun 24 '15 at 15:15
  • Why would I need to add SmtpAppender and AdoNetAppender in the root? – DanCode Jun 24 '15 at 15:58
  • In my case I needed the addition appenders, but you can remove them in your case. Glad you got it to work in the end. – Sameer Chauhan Jun 29 '15 at 07:49
0

Try specifying the config file in your AssemblyInfo.cs, mine is like this:

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

Add an XML file log4net.config to your project, use this to start with:

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

  </configSections>
  <log4net>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="C:\log.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="1MB" />
      <filter type="log4net.Filter.LevelRangeFilter">
        <acceptOnMatch value="true" />
        <levelMin value="INFO" />
        <levelMax value="FATAL" />
      </filter>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="=========================================
                                  %nLEVEL:........%-5level
                                  %nTIMESTAMP:....%date 
                                  %nMessage:
                                  %n%m
                                  %nUsername: %username
                                  %n=========================================
                                  %n" />
      </layout>
    </appender>

    <root>
      <level value="all" />
      <appender-ref ref="RollingFileAppender" />
      <appender-ref ref="SmtpAppender" />
    </root>
  </log4net>
</configuration>

then put this in your app (mine was just a simple console app that only logged "Test".

class Program
{
    private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

    static void Main(string[] args)
    {
        log.Error("Test");
        Console.ReadLine();

    }
}
  • I tried that before but it did not work. Is the log suppose to appear in the output window? – DanCode Jun 24 '15 at 17:20
  • is your config file named Log4net.config? I know if i leave out the ConfigFile="log4net.config", nothing is logged. Did you set the config file to content, copy always in the properties? – Theodosius Von Richthofen Jun 24 '15 at 17:21
  • My config file is called app.config. Yes, I did set the build action to Content and Copy to Output Directory as always in the properties. – DanCode Jun 24 '15 at 17:23
  • just made a simple program that log4net worked fine in. all i did was add the line i originally had in the answer, and the edits and thats it. try doing it this way before you complicate it with LoggerView class etc. – Theodosius Von Richthofen Jun 24 '15 at 18:26
  • once you can get that going, try putting your additions in. let me know if that works for you – Theodosius Von Richthofen Jun 24 '15 at 18:32
  • When I start a new console project and do the steps that you provided, it worked for me. However, when I add a new console project to my project and do the same step as you instructed, the logger did not show. – DanCode Jun 24 '15 at 19:28
  • are you still trying to put the log4net config inside of app.config? are you using nuget to install the log4net package? – Theodosius Von Richthofen Jun 24 '15 at 21:00
  • I have gotten my logger to save successfully. Thank you so much everyone! Unfortunately, I do not have enough reputation to give any +1. – DanCode Jun 25 '15 at 16:01