0

I wrote my own appender to be able to output the log in a WPF TextBox. Here it is:

public class TextBoxAppender : AppenderSkeleton
{
    private TextBox _tb;
    public TextBoxAppender(TextBox tb)
    {
        _tb = tb;
    }

    protected override void Append(LoggingEvent loggingEvent)
    {
        _tb.Text += loggingEvent.RenderedMessage + "\n";
    }
}

I initialized the log and added the appender like so:

var myTextBox = ... // get WPF TextBox from somewhere
var type = GetType();
var assembly = type.Assembly;
var loggerRepo = LogManager.GetRepository(assembly);
var rootLogger = ((Hierarchy)loggerRepo).Root;
Log = LogManager.GetLogger(assembly, type);
var tbAppender = new TextBoxAppender(myTextBox);

rootLogger.AddAppender(tbAppender);
rootLogger.Hierarchy.Configured = true;

And it works. I did not specify any layout, so it just uses some default layout: If I write Log.Debug("My Message") then the output is just "My Message".

Now I want to specify my own layout. So I wrote these lines:

PatternLayout layout = new PatternLayout();
layout.ConversionPattern = "%level - %message%newline"; // my layout
layout.ActivateOptions();
tbAppender.Layout = layout;
tbAppender.ActivateOptions();

and put them in the empty line between var tbAppender = ... and rootLogger.AddAppender.... But it doesn't change the layout at all! What am I doing wrong?

Kjara
  • 2,504
  • 15
  • 42

1 Answers1

1

As I understand it, the loggingEvent is passed to all your active appenders, and hence does have any knowledge of the layout (which is a property of the appender).

I think the solution is to call the appenders RenderLoggingEvent method, ie change

 _tb.Text += loggingEvent.RenderedMessage + "\n";

to

 _tb.Text += RenderLoggingEvent(loggingEvent) + "\n";
sgmoore
  • 15,694
  • 5
  • 43
  • 67