본문 바로가기

언어/C#

log4net TextBox Appender

출처: http://www.hind.pe.kr/1248

C#에서 TextBox에 log4net을 띄우기 위한 방법.

TextBox가 위치한 Form의 생성자 안에서 TextBoxAppender.SetupTextBoxAppend 를 호출하면 된다.
인자값으로는 Textbox 인스턴스와 PatternLayout에 넣는 PatternFormat 문자열만 넣으면 된다.



TextBoxAppender.SetupTextBoxAppend(txtLogs, "%date{HH:mm:ss,fff} %-5level %-33logger - %message%newline");

namespace Logger
{
    public class TextBoxAppender : AppenderSkeleton
    {
        static public void SetupTextBoxAppend(TextBox textbox, string sLayerFormat)
        {
            TextBoxAppender textBoxAppender = new TextBoxAppender();
            textBoxAppender.AppenderTextBox = textbox;
            textBoxAppender.Threshold = log4net.Core.Level.All;
            ILayout layout = null;
            if (string.IsNullOrEmpty(sLayerFormat))
            {
                layout = new log4net.Layout.SimpleLayout();
            }
            else
            {
                PatternLayout layoutPattern = new PatternLayout(sLayerFormat);
                layout = layoutPattern;                                
            }            
            textBoxAppender.Layout = layout;
            textBoxAppender.Name = string.Format("TextBoxAppender_{0}", textbox.Name);            
            textBoxAppender.ActivateOptions();
            Hierarchy h = (Hierarchy)log4net.LogManager.GetRepository();
            h.Root.AddAppender(textBoxAppender);
        }


        private TextBox _textBox;
        public TextBox AppenderTextBox
        {
            get
            {
                return _textBox;
            }
            set
            {
                _textBox = value;
            }
        }

        override protected bool RequiresLayout
        {
            get { return true; }
        }

        protected override void Append(log4net.Core.LoggingEvent loggingEvent)
        {
            if (_textBox == null)
                return;
            try
            {             
                string sMessage  = base.RenderLoggingEvent(loggingEvent);
                _textBox.BeginInvoke(new WriteMessageHandler(WriteMessage), sMessage);
            }
            catch
            {

            }
        }

        private delegate void WriteMessageHandler(string sMessage);

        private void WriteMessage(string sMessage)
        {
                _textBox.AppendText(sMessage);                
                _textBox.Select(_textBox.TextLength - 1, 0);
                _textBox.ScrollToCaret();
        }
    }
}



'언어 > C#' 카테고리의 다른 글

NLog.Windows.Forms  (0) 2018.03.22
Rich text box appender  (0) 2018.03.20
Log4Net ScrollingTextBox  (0) 2018.03.20
DevApps - Podcast 03 - Comment tracer avec NLog ?  (0) 2018.03.20
Academy of programmer - How to use NLog in WinForms app  (0) 2018.03.20