How to include log4net for a class library?

Quan Mai picture Quan Mai · Jan 6, 2011 · Viewed 28.5k times · Source

I want to implement logging function into a class library, which is itself referenced in a webservice. I tried to add app.config and did everything needed, but it seems that when an exception is thrown, log4net simply does nothing.

my app.config

<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>
  <log4net>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="D:\\mylogfile.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="5" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <filter type="log4net.Filter.StringMatchFilter">
        <stringToMatch value="test" />
      </filter>
      <filter type="log4net.Filter.StringMatchFilter">
        <stringToMatch value="error" />
      </filter>
      <filter type="log4net.Filter.DenyAllFilter" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %level %logger - %message%newline%exception" />
      </layout>
    </appender>
    <root>
      <level value="INFO"/>
      <appender-ref ref="RollingFileAppender"/>
      <appender-ref ref="ConsoleAppender" />
    </root>
  </log4net>

in AssemblyInfo.cs:

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "app.config")]

in LogManager.cs:

private static readonly ILog Log = log4net.LogManager.GetLogger
            (MethodBase.GetCurrentMethod().DeclaringType);
public static void WriteLog(Exception ex)
{
    Log.Error(ex);
}

Can you please tell me what's wrong? How can I get log4net working for my class library?

Thank you

Answer

hungryMind picture hungryMind · Jan 6, 2011

At runtime, config file is always used from host application, unless declared explicitly. Here in case, web.config is being used not app.cofig. Rather mention some other custom config file name and ensure that file is copied in virtual directory of web service. Also as chibacity said, ensure permission on log file. Better keep it in app_data folder for web service host.