My Technical Notes

Wednesday, 22 June 2016

Log4net: Simple Console Application that Uses MemoryAppender

This simple example uses log4net version 2.0.3 to write to a `MemoryAppender` which is the read to produce a string at the end of all the log messages.

Installing Log4net

We first download and install log4net version 2.0.3 using NuGet Package Manager Console:

Install-Package -Id log4net -Version 2.0.3

Configuring Log4net via config file

We place the following configuration in our app/web.config file. It declares an appender called `MemoryAppender` which we will access through the C# code later. It also adds a config section under `configSections` so that log4net is configured.

  <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  <appender name="MemoryAppender" type="log4net.Appender.MemoryAppender">
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date{HH:mm:ss}|%-5level|%message|%logger|%M%newline"/>
    <appender-ref ref="MemoryAppender"/>

Invoking Log4net's XML Configurator

Follow this post to invoke log4net's XML Configurator.

Converting Logs to a String

To get a string representation of all the logged statements, we use the following code. Note that the `result` variable will be set to the log data.

var hierarchy = (Hierarchy)log4net.LogManager.GetRepository();
var memoryAppender = (MemoryAppender)hierarchy.Root.GetAppender("MemoryAppender");
var events = memoryAppender.GetEvents();
string result = "";
using (var writer = new System.IO.StringWriter())
    foreach (var ev in events)
        memoryAppender.Layout.Format(writer, ev);
    result = writer.ToString();

No comments: