unable to get log4net working with .net windows service

Null Reference picture Null Reference · May 6, 2013 · Viewed 39.5k times · Source

I have a windows service with an app.config and a log4net.config.

app.config:

  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net configSource="log4net.config" />

log4net.config:

<log4net>
  <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
    <param name="File" value="D:\Projects\Integration\Interface Module\bin\Logs\MyFirstLogger.log"/>
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <appendToFile value="true" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="2" />
    <maximumFileSize value="1MB" />
    <staticLogFileName value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n"/>
    </layout>
  </appender>

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

I have added this in AssemblyInfo.cs too:

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

And in one of my classes, I have:

private readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

and

_log.Info(content);

I have given all users full permissions to my Logs folder.

My bin folder (which the service is running from) has both my app.config and log4net.config.

But no logging file got generated. What settings did I miss?

Updated on 4-March-2014

If you are using a separate config file like I did (log4net.config), do remember to set the Copy to output directory setting to Copy always in the Solution Explorer

Answer

YantingChen picture YantingChen · Apr 20, 2016

Please note that when the process is run as Windows Service, Environment.CurrentDirectory will be "C:\Windows\system32"

So if you put the log4net configuration file (log4net.config) next to your *.exe, you can use the following code to configure log4net.

var assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
XmlConfigurator.Configure(new FileInfo(Path.Combine(assemblyFolder, "log4net.config")));