log4net - Custom property logging

c#, log4net, log4net-configuration

Solution

I just wrote a custom pattern, which allows to read properies of the message object.

public class ReflectionReader : PatternLayoutConverter
{
    public ReflectionReader()
    {
        _getValue = GetValueFirstTime;
    }

    protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
    {
        writer.Write(_getValue(loggingEvent.MessageObject));
    }

    private Func<object, String> _getValue;
    private string GetValueFirstTime(object source)
    {
        _targetProperty = source.GetType().GetProperty(Option);
        if (_targetProperty == null)
        {
            _getValue = x => "<NULL>";
        }
        else
        {
            _getValue = x => String.Format("{0}", _targetProperty.GetValue(x, null));
        }
        return _getValue(source);
    }

    private PropertyInfo _targetProperty;
}

Combine with this:

public class ReflectionLayoutPattern : PatternLayout
{
    public ReflectionLayoutPattern()
    {
        this.AddConverter("item", typeof(ReflectionReader));
    }
}

Config looks like this:

<layout type="MyAssembly.MyNamespace.ReflectionLayoutPattern, MyAssembly">
  <conversionPattern value="[%item{Id}]&#9;%message%newline" />
</layout>

Problem

I got use the following class to print out messages using log4net: ``` public class Message { public String Text { get; set; } public int Id { get; set; } public override string ToString() { return Text; } } ``` I use `Logger.Info(MessageInstance)`, so log4net just invokes the `ToString` method and prints out the message. I would like to also log the `Id` property of the message object, but I cannot figure out how to achive this. My conversion pattern looks similiar to this: ``` <conversionPattern value="%date %-5level %message%newline" /> ``` I tried adding `%message{Id}` but that would just print the whole message twice. Any Suggestions?

Original source