Category name´╝ÜLogging

Log4net Separate configuration file and custom data

Separate configuration file for log4net settings

We always store the configuration stuff in the app.config or web.config files but at our current project we want to store settings that are different between environments outside of the default configuration files. Custom application settings and connectionstrings are stored in seperate configuration files and the log4net settings had to move too. Our configuration files are now named:

  • web.config/app.config
  • connectionstrings.config
  • appsettings.config
  • log4net.config

Getting log4net configured to read the settings from the log4net.config file was easy. It only needed the following attribute statement in the assembly info file:

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

Custom properties

We use the AdoNetAppender to log to the database but use several hosts to log to the same database table. We wanted to store additional information to each log message to identify which host is logging and which version it is running.


private void ConfigureLogging()
    System.Reflection.Assembly assembly;
    System.Diagnostics.FileVersionInfo versionInfo;
    string versionText;

    assembly = System.Reflection.Assembly.GetExecutingAssembly();
    versionInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(assembly.Location);
    versionText = versionInfo.FileVersion;

    log4net.GlobalContext.Properties[“Host”] = System.Net.Dns.GetHostName();
    log4net.GlobalContext.Properties[“Version”] = VersionText;


Most appenders set the ConversationPattern parameter. To following conversation pattern uses the above custom properties. To use a custom property add %property{CustomPropertyName} to your conversation pattern.

<param name=”ConversationPattern” value=”%d [%property{Host}][%property{Version}][%t] %-5p %c – %m%n” />

The AdoNetAppender only needs additional parameter mappings. Make sure that the parameter names match the custom property names.

    <parameterName value=”@host” />
    <dbType value=”String” />
    <size value=”50″ />
    <layout type=”log4net.Layout.ExceptionLayout” />
    <parameterName value=”@version” />
    <dbType value=”String” />
    <size value=”23″ />
    <layout type=”log4net.Layout.ExceptionLayout” />

Et voila! We now get the hostname and version info logged too.

  • Recent Posts
  • Recent Comments
  • Archives
  • Categories
  • Meta