Monday, November 7, 2011

Log4net in a not-.NET application

Hi everyone,

So I've moved on to a couple of other projects (Recordings is now live and complete enough). One such project is an old legacy VB6 application that I'm extending with C# via COM interop.

The situation I have is this:
  • I would like to use Log4net in the C# code, compiled as DLLs and imported into the VB6  project
  • I would like to configure Log4net via an xml config file, but it won't have to change at runtime. 
So, here's how that's accomplished:

The log4net.config file is added as an embedded resource in the C# class library project. It looks like this:

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

<log4net>
  <appender name="DebugFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="J:\Chris\Source\citysiege\main\logs\" />
    <appendToFile value="true" />
    <rollingStyle value="Date" />
    <maxSizeRollBackups value="30" />
    <datePattern value="yyyy-MM-dd'.txt'" />
    <staticLogFileName value="false" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
    </layout>
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
  </appender>

  <root>
    <level value="DEBUG" />
    <appender-ref ref="DebugFileAppender" />
  </root>
</log4net>

A static class method serves as a wrapper around the log4net library and an entry point to configure it:

            var assembly = Assembly.GetExecutingAssembly();
            var stream = assembly.GetManifestResourceStream("CitySiegeLogic.log4net.config");
            log4net.Config.XmlConfigurator.Configure(stream);

Simple right? Well, took a little while to figure out. Also, if the config file is in a subfolder be sure to add that to the path along with the namespace, so for example "CitySiegeLogic.logging.log4net" if its under /logging.

No comments:

Post a Comment