通过Xml文件配置log4net TextBoxAppender(自定义appender)

时间:2013-01-01 21:58:33

标签: c# log4net log4net-appender

这是我的问题的后续内容:Flexible Logging Interface...

我现在想为我的WinForms 2.0应用程序为多行TextBox编写一个自定义log4net appender。其中一个StackOverflow成员devdigital已经向我指出了这个链接:

TextBox Appender

但是,本文没有介绍如何通过Xml文件配置这样的appender。配置此appender的唯一问题是我们需要将对TextBox对象的引用传递给此appender。

所以可以使用Xml文件配置它吗?或者只能以编程方式配置这些appender?有哪些选项可以将其设置为可配置或松散耦合,可能是使用Xml文件和代码的组合?

感谢。

7 个答案:

答案 0 :(得分:19)

这取决于你如何配置log4net,但是当log4net读取配置时,通常不会创建任何表单(因此也就是textBoxes)。因此,您需要为表单和文本框名称创建属性。您应该检查表单是否已打开,并且在附加日志记录事件之前提供了文本框。另外,从AppenderSkeleton继承而不是从头开始实现IAppender

public class TextBoxAppender : AppenderSkeleton
{
    private TextBox _textBox;
    public string FormName { get; set; }
    public string TextBoxName { get; set; }

    protected override void Append(LoggingEvent loggingEvent)
    {
        if (_textBox == null)
        {
            if (String.IsNullOrEmpty(FormName) || 
                String.IsNullOrEmpty(TextBoxName))
                return;

            Form form = Application.OpenForms[FormName];
            if (form == null)
                return;

            _textBox = form.Controls[TextBoxName] as TextBox;
            if (_textBox == null)
                return;

            form.FormClosing += (s, e) => _textBox = null;
        }

        _textBox.AppendText(loggingEvent.RenderedMessage + Environment.NewLine);
    }
}

配置很简单(log4net将读取xml元素并为具有相同名称的属性提供值):

<appender name="textbox" type="Foo.TextBoxAppender, Foo">
  <formName value="Form1"/>
  <textBoxName value="textBox1"/>
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date %-5level %logger - %message" />
  </layout>      
</appender>
<root>
  <level value="INFO" />
  <appender-ref ref="textbox"/>
</root>

我没有提供任何与多线程和线程同步相关的错误处理代码或代码,因为问题是关于appender配置。

答案 1 :(得分:15)

这里是所有上层注释的更新版本:线程安全,不锁定应用程序并使用转换模式:

namespace MyNamespace
{

    public class TextBoxAppender : AppenderSkeleton
    {
        private TextBox _textBox;
        public TextBox AppenderTextBox
        {
            get
            {
                return _textBox;
            }
            set
            {
                _textBox = value;
            }
        }
        public string FormName { get; set; }
        public string TextBoxName { get; set; }

        private Control FindControlRecursive(Control root, string textBoxName)
        {
            if (root.Name == textBoxName) return root;
            foreach (Control c in root.Controls)
            {
                Control t = FindControlRecursive(c, textBoxName);
                if (t != null) return t;
            }
            return null;
        }

        protected override void Append(log4net.Core.LoggingEvent loggingEvent)
        {
            if (_textBox == null)
            {
                if (String.IsNullOrEmpty(FormName) ||
                    String.IsNullOrEmpty(TextBoxName))
                    return;

                Form form = Application.OpenForms[FormName];
                if (form == null)
                    return;

                _textBox = (TextBox)FindControlRecursive(form, TextBoxName);
                if (_textBox == null)
                    return;

                form.FormClosing += (s, e) => _textBox = null;
            }
            _textBox.BeginInvoke((MethodInvoker)delegate
            {
                _textBox.AppendText(RenderLoggingEvent(loggingEvent));
            });
        }
    }

}

配置,将其放在app.config中:

<appender name="textboxAppender" type="MyNamespace.TextBoxAppender, MyNamespace">
  <formName value="MainForm"/>
  <textBoxName value="textBoxLog"/>
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  </layout>
</appender>
<root>
  <level value="DEBUG" />
  <appender-ref ref="RollingFileAppender" />
  <appender-ref ref="textboxAppender" />
</root>   

答案 2 :(得分:7)

我修改了appender以使用多线程。 另外,我附上了代码配置。

此致 多兰基尔托

追加程序:

public class TextBoxAppender : AppenderSkeleton
{
    private TextBox _textBox;
    public TextBox AppenderTextBox
    {
        get
        {
            return _textBox;
        }
        set
        {
            _textBox = value;
        }
    }
    public string FormName { get; set; }
    public string TextBoxName { get; set; }

    private Control FindControlRecursive(Control root, string textBoxName)
    {
        if (root.Name == textBoxName) return root;
        foreach (Control c in root.Controls)
        {
            Control t = FindControlRecursive(c, textBoxName);
            if (t != null) return t;
        }
        return null;
    }

    protected override void Append(log4net.Core.LoggingEvent loggingEvent)
    {
        if (_textBox == null)
        {
            if (String.IsNullOrEmpty(FormName) ||
                String.IsNullOrEmpty(TextBoxName))
                return;

            Form form = Application.OpenForms[FormName];
            if (form == null)
                return;

            _textBox = (TextBox)FindControlRecursive(form, TextBoxName);
            if (_textBox == null)
                return;

            form.FormClosing += (s, e) => _textBox = null;
        }
        _textBox.Invoke((MethodInvoker)delegate
        {
            _textBox.AppendText(loggingEvent.RenderedMessage + Environment.NewLine);
        });
    }
}

配置:

           var textBoxAppender = new Util.TextBoxAppender();
        textBoxAppender.TextBoxName = "textLog";
        textBoxAppender.FormName = "MainTarget";
        textBoxAppender.Threshold = log4net.Core.Level.All;
        var consoleAppender = new log4net.Appender.ConsoleAppender { Layout = new log4net.Layout.SimpleLayout() };
        var list = new AppenderSkeleton[] { textBoxAppender, consoleAppender };
        log4net.Config.BasicConfigurator.Configure(list);

答案 3 :(得分:2)

附加到文本框的实际行应该是......

_textBox.AppendText(RenderLoggingEvent(loggingEvent));

...如果你想利用模式布局。否则,它只发送消息文本(默认布局)。

答案 4 :(得分:1)

以上Klodoma的样本非常好。如果将文本框更改为richtextbox,则可以对输出执行更多操作。以下是一些按级别对消息进行颜色编码的代码:

        System.Drawing.Color text_color;

        switch (loggingEvent.Level.DisplayName.ToUpper())
        {
            case "FATAL":
                text_color = System.Drawing.Color.DarkRed;
                break;

            case "ERROR":
                text_color = System.Drawing.Color.Red;
                break;

            case "WARN":
                text_color = System.Drawing.Color.DarkOrange;
                break;

            case "INFO":
                text_color = System.Drawing.Color.Teal;
                break;

            case "DEBUG":
                text_color = System.Drawing.Color.Green;
                break;

            default:
                text_color = System.Drawing.Color.Black;
                break;
        }

        _TextBox.BeginInvoke((MethodInvoker)delegate
        {
            _TextBox.SelectionColor = text_color;
            _TextBox.AppendText(RenderLoggingEvent(loggingEvent));
        });

如果你真的想要,可以用与ColorConsoleAppender相同的方式从log4net配置映射颜色,但是我将其留给下一个编码器偶然发现这个样本......

答案 5 :(得分:1)

如果您想在自己的多个位置进行日志记录,我希望采用以下方法 应用。此方法提供了动态更改控件实例的灵活性 通过代码。

TextBoxAppender

public class TextBoxAppender : AppenderSkeleton
    {
        public RichTextBox RichTextBox { get; set; }

        protected override void Append(LoggingEvent loggingEvent)
        {
            Action operation = () => { this.RichTextBox.AppendText(RenderLoggingEvent(loggingEvent)); };
            this.RichTextBox.Invoke(operation);
        }
    }

分配文本框实例的代码。在开始执行日志记录的过程之前执行此操作。

 var appender = LogManager.GetRepository().GetAppenders().Where(a => a.Name == "TextBoxAppender").FirstOrDefault();
 if (appender != null)
       ((TextBoxAppender)appender).RichTextBox = this.richTextBoxLog;

配置

<log4net debug="false">
    <appender name="TextBoxAppender" type="SecurityAudit.UI.TextBoxAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
      </layout>
    </appender>
    <root>
      <priority value="DEBUG" />
      <appender-ref ref="TextBoxAppender" />
    </root>
  </log4net>

答案 6 :(得分:0)

这是klodoma答案的WPF / XAML版本

  public class TextBoxAppender : AppenderSkeleton {
    private TextBox AppenderTextBox { get; set; }
    private Window window;

    public string WindowName { get; set; }
    public string TextBoxName { get; set; }

    private T FindControl<T>(Control root, string textBoxName) where T:class{
        if (root.Name == textBoxName) {
            return root as T;
        }

        return root.FindName(textBoxName) as T;
    }

    protected override void Append(log4net.Core.LoggingEvent loggingEvent) {
        if (window == null || AppenderTextBox == null) {
            if (string.IsNullOrEmpty(WindowName) ||
                string.IsNullOrEmpty(TextBoxName))
                return;

            foreach (Window window in Application.Current.Windows) {
                if (window.Name == WindowName) {
                    this.window = window;
                }
            }
            if (window == null)
                return;

            AppenderTextBox = FindControl<TextBox>(window, TextBoxName);
            if (AppenderTextBox == null)
                return;

            window.Closing += (s, e) => AppenderTextBox = null;
        }
        window.Dispatcher.BeginInvoke( new Action(delegate {
            AppenderTextBox.AppendText(RenderLoggingEvent(loggingEvent));
        }));
    }

和日志配置

 <appender name="textboxAppender" type="Namespace.TextBoxAppender, Namespace">
<windowName value="Viewer"/>
<textBoxName value="LogBox"/>
<layout type="log4net.Layout.PatternLayout">
  <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>

别忘了给您的窗口起一个名字(必须与窗口类型名称不同)