c# log4net 日志输出到 本地文件 textbox listview DEMO

网上很多配置log4net的方法,但是排行靠前的 根本就没有说明清除,导致浪费了两个小时来搞清楚如何配置,真是无语,特写此文,给那些刚接触log4net的朋友



1,参考链接

http://blog.sina.com.cn/s/blog_642e41c201014pml.html


此方法是直接将配置文件配置在app.config

 
    
    

第二种方式就是单独将配置文件配置在log4net.config中,网上大多数都是这种方法,但是却没有说明关键的一步

参考链接

http://www.cnblogs.com/zfanlong1314/p/3662679.html

1. 新建一个配置文件,log4net.config配置方法同成web.config或app.config一致;
2.如果windows应用程序请把配置文件设为:复制到输出目录 修改方法:在log4net.config上右击-->属性--->把 "复制到输出目录"  值改为 true ;
3.在要用到log4的地方命名空间上边加上:[assembly: log4net.Config.XmlConfigurator(ConfigFile =  "log4net.config" , Watch =  true )]
4,vb.net是在AssemblyInfo.vb(ide上看不到,需要在文件夹搜索到)上添加
<Assembly: log4net.Config.XmlConfigurator(ConfigFile:="log/log4net.config", Watch:=True)> 


3,自定义textbox日志输出

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 log4myself
{
    /// 
    /// 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);
    /// 
    public class TextBoxBaseAppender : AppenderSkeleton
    {
        public TextBoxBase TextBox { get; set; }

        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)
            {
                printf(str);
            }
            else
            {
                this.TextBox.BeginInvoke((MethodInvoker)delegate
                {
                    if (!this.TextBox.IsHandleCreated)
                    {
                        return;
                    }

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

        private void printf(string str)
        {
            //若是超过10行 则清楚
            if (TextBox.Lines.Length > 50)
            {
                TextBox.Clear();
            }
            this.TextBox.AppendText(str);
        }
    }
}

form中的代码为

            //读取配置文件的信息
            log1 = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
            
            //设置textbox打印日志
            var logPattern = "%d{yyyy-MM-dd HH:mm:ss} --%-5p-- %m%n";
            var textBox_logAppender = new TextBoxBaseAppender()
            {
                TextBox = this.textBox1,//注释后 就只有文件log
                Layout = new PatternLayout(logPattern)
            };
            //相当于root标签下的   
            log4net.Config.BasicConfigurator.Configure(textBox_logAppender);


listview代码为

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 log4myself
{
    public class ListViewBaseAppender : AppenderSkeleton
    {
        public ListView listView { get; set; }

        public ListViewBaseAppender()
        {
        }

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

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

            if (this.listView.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.listView.InvokeRequired)
            {
                printf(str);
            }
            else
            {
                this.listView.BeginInvoke((MethodInvoker)delegate
                {
                    if (!this.listView.IsHandleCreated)
                    {
                        return;
                    }

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

                    printf(str);
                });
            }
        }

        private void printf(string str)
        {
            if (listView.Items.Count>50)
            {
                listView.Items.Clear();
            }

            ListViewItem item = new ListViewItem();
            item.Text = str.ToString(); 

            listView.BeginUpdate();
            listView.Items.Add(item);
            listView.Items[listView.Items.Count - 1].EnsureVisible();//滚动到最后  
            listView.EndUpdate();  
        }
    }
}


demo 下载 http://download.csdn.net/download/sc6231565/9791817

你可能感兴趣的:(C#)