自编写的appender不使用指定的布局

时间:2017-06-26 11:10:58

标签: c# log4net log4net-appender

我编写了自己的appender,以便能够在WPF TextBox中输出日志。这是:

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

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

我初始化了日志并添加了这样的appender:

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;

它有效。我没有指定任何布局,所以它只使用了一些默认布局:如果我写Log.Debug("My Message"),那么输出只是"My Message"

现在我要指定自己的布局。所以我写了这些文字:

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

并将它们放在var tbAppender = ...rootLogger.AddAppender...之间的空行中。但它根本不会改变布局!我做错了什么?

1 个答案:

答案 0 :(得分:1)

据我了解,loggingEvent传递给所有活动的appender,因此对布局有任何了解(这是appender的属性)。

我认为解决方案是调用appender RenderLoggingEvent方法,即更改

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

 _tb.Text += RenderLoggingEvent(loggingEvent) + "\n";