Poppa Wallace

Poppa Wallace

  • NA
  • 189
  • 24.4k

log4net custom appender

Dec 19 2016 8:44 AM
Hello all, I have a application that was originally a console App. Most of the stuff I have now changed to a more friendly UI using winforms. The only thing I am having problems with is getting log4net to append to a textbox.
 
my log4net config file. 
and my appender class. in my mainform ServerGUI I call log.Warn("Testing warning");
 
but it does not append to my textbox.
 
Thanks 
 
 
 
  1. xml version="1.0" encoding="utf-8" ?>  
  2.   
  3.   
  4. <log4net>  
  5.   
  6.   <appender name="textboxAppender" type="ServerGUI.TextBoxAppender, ServerGUI">  
  7.   <formName value="ServerGUI"/>  
  8.   <textBoxName value="txtConsole"/>  
  9.   <layout type="log4net.Layout.PatternLayout">  
  10.     <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />  
  11.   layout>  
  12. appender>  
  13. <root>  
  14.   <level value="ALL" />  
  15.     
  16.   <appender-ref ref="textboxAppender" />  
  17. root>     
  18.   
  19. log4net>  
  1. public class TextBoxAppender : AppenderSkeleton  
  2.   {  
  3.       private TextBox _textBox;  
  4.       public TextBox AppenderTextBox  
  5.       {  
  6.           get  
  7.           {  
  8.               return _textBox;  
  9.           }  
  10.           set  
  11.           {  
  12.               _textBox = value;  
  13.           }  
  14.       }  
  15.       public string FormName { getset; }  
  16.       public string TextBoxName { getset; }  
  17.   
  18.       private Control FindControlRecursive(Control root, string textBoxName)  
  19.       {  
  20.           if (root.Name == textBoxName) return root;  
  21.           foreach (Control c in root.Controls)  
  22.           {  
  23.               Control t = FindControlRecursive(c, textBoxName);  
  24.               if (t != nullreturn t;  
  25.           }  
  26.           return null;  
  27.       }  
  28.   
  29.       protected override void Append(log4net.Core.LoggingEvent loggingEvent)  
  30.       {  
  31.           if (_textBox == null)  
  32.           {  
  33.               if (String.IsNullOrEmpty(FormName) ||  
  34.                   String.IsNullOrEmpty(TextBoxName))  
  35.                   return;  
  36.   
  37.               Form form = Application.OpenForms[FormName];  
  38.               if (form == null)  
  39.                   return;  
  40.   
  41.               _textBox = (TextBox)FindControlRecursive(form, TextBoxName);  
  42.               if (_textBox == null)  
  43.                   return;  
  44.   
  45.               form.FormClosing += (s, e) => _textBox = null;  
  46.           }  
  47.           _textBox.BeginInvoke((MethodInvoker)delegate  
  48.           {  
  49.               _textBox.AppendText(RenderLoggingEvent(loggingEvent));  
  50.           });  
  51.       }  
  52.   }  
 
 

Answers (1)