Configuring log4net TextBoxAppender (custom appender) via Xml file

后端 未结 7 2115

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:40

    Here is a WPF/XAML version of klodoma's answer

      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(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(window, TextBoxName);
                if (AppenderTextBox == null)
                    return;
    
                window.Closing += (s, e) => AppenderTextBox = null;
            }
            window.Dispatcher.BeginInvoke( new Action(delegate {
                AppenderTextBox.AppendText(RenderLoggingEvent(loggingEvent));
            }));
        }
    

    and the log config

     
    
    
    
      
    
    

    Don't forget to give your window a name (must be different to the window type name)

提交回复
热议问题