mrfangzheng

Hope and fear are useless. Be confident, and always be prepared for the worst.
  首页  :: 新随笔  :: 联系 :: 管理

Log4Net: TextBoxBaseAppender

Posted on 2012-11-29 18:43  mrfangzheng  阅读(668)  评论(0编辑  收藏  举报
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net.Appender;
using System.Windows.Forms;
using log4net.Core;
using log4net.Layout;

namespace UI
{
    /// <summary>
    
/// Usage:
    
///     log4net.Config.BasicConfigurator.Configure();
    
///     var logPattern = "%date [%thread] %-5level %logger !%M - %message%newline";
    
///     var logAppender = new TextBoxBaseAppender()
    
///     {
    
///         TextBox = this.textBox2,
    
///         Layout = new PatternLayout(logPattern)
    
///     };
    
///     
    
///     ((log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.GetLoggerRepository()).Root.AddAppender(logAppender);
    
/// </summary>
    public class TextBoxBaseAppender : AppenderSkeleton
    {
        public TextBoxBase TextBox { getset; }

        public TextBoxBaseAppender()
        {
        }

        protected override void Append(LoggingEvent loggingEvent)
        {
            if (this.TextBox == null)
            {
                return;
            }

            if(!this.TextBox.IsHandleCreated)
            {
                return;
            }

            if(this.TextBox.IsDisposed)
            {
                return;
            }

            var patternLayout = this.Layout as PatternLayout;

            var str = string.Empty;
            if (patternLayout != null)
            {
                str = patternLayout.Format(loggingEvent);

                if (loggingEvent.ExceptionObject != null)
                {
                    str += loggingEvent.ExceptionObject.ToString() + Environment.NewLine;
                }
            }
            else
            {
                str = loggingEvent.LoggerName + "-" + loggingEvent.RenderedMessage + Environment.NewLine;
            }

            if (!this.TextBox.InvokeRequired)
            {
                this.TextBox.AppendText(str);
            }
            else
            {
                this.TextBox.BeginInvoke((MethodInvoker)delegate
                {
                    if (!this.TextBox.IsHandleCreated)
                    {
                        return;
                    }

                    if (this.TextBox.IsDisposed)
                    {
                        return;
                    }
                    this.TextBox.AppendText(str);
                });
            }
        }
    }
}