Configuring log4net TextBoxAppender (custom appender) via Xml file

后端 未结 7 2082

This is in followup to my question: Flexible Logging Interface...

I now want to write a custom log4net appender for a multiline TextBox, for my WinForms 2.0 applicat

7条回答
  •  醉梦人生
    2020-12-03 05:50

    here is an updated version of all upper comments: thread safe, doesn't lock the application and uses the conversion pattern:

    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));
                });
            }
        }
    
    }
    

    The configuration, place this in app.config:

    
      
      
      
        
      
    
    
      
      
      
       
    

提交回复
热议问题