Configuring log4net TextBoxAppender (custom appender) via Xml file

后端 未结 7 2090

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

    I modified the appender to work with multithreading. Also, I attached the code configuration.

    Regards, Dorin

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

    Configuration:

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

提交回复
热议问题