码迷,mamicode.com
首页 > Web开发 > 详细

log4net配置

时间:2015-01-22 20:02:25      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:

mysql数据库,创建这个表

DROP TABLE IF EXISTS `t_errorlog`;
CREATE TABLE `t_errorlog` (
  `rowid` int(11) NOT NULL AUTO_INCREMENT,
  `log_date` datetime DEFAULT NULL COMMENT ‘log时间‘,
  `Thread` varchar(255) DEFAULT NULL COMMENT ‘线程‘,
  `Level` varchar(100) DEFAULT NULL COMMENT ‘级别‘,
  `logger` varchar(510) DEFAULT NULL COMMENT ‘名称空间‘,
  `message` longtext COMMENT ‘出現錯誤讯息‘,
  `method` varchar(50) DEFAULT NULL COMMENT ‘出错的方法‘,
  PRIMARY KEY (`rowid`)
) ENGINE=InnoDB AUTO_INCREMENT=1403 DEFAULT CHARSET=utf8;

1.第一步:把log4net加入到引用

2.第二步:配置web.config 可以配置成数据库或者文件或者操作系统事件里面

  <configSections>
    <section name="log4net" type="System.Configuration.IgnoreSectionHandler"/>
  </configSections>
  <log4net>
    <appender name="ADONetAppender_SqlServer" type="log4net.Appender.AdoNetAppender">
      <bufferSize value="1"/>
      <connectionType value="MySql.Data.MySqlClient.MySqlConnection, MySql.Data"/>
      <connectionString value="Server=192.168.19.10;database=user;user=gigade;pwd=ge20110831;charset=‘utf8‘" />
      <commandText value="insert into t_errorlog (`log_date`,`thread`,`level`,`logger`,`message`,`method`) values (@log_date, @thread, @log_level, @logger, @content,@method)"/>
      <parameter>
        <parameterName value="@log_date"/>
        <dbType value="DateTime"/>
        <layout type="log4net.Layout.RawTimeStampLayout"/>
      </parameter>
      <parameter>
        <parameterName value="@thread"/>
        <dbType value="String"/>
        <size value="255"/>
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%thread"/>
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@log_level"/>
        <dbType value="String"/>
        <size value="50"/>
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%level"/>
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@logger"/>
        <dbType value="String"/>
        <size value="255"/>
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%logger"/>
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@content"/>
        <dbType value="String"/>
        <size value="4000"/>
        <layout type="Admin.gigade.Log4NetCustom.CustomLayout">
          <conversionPattern value="%property{Content}"/>
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@method"/>
        <dbType value="String"/>
        <size value="50"/>
        <layout type="Admin.gigade.Log4NetCustom.CustomLayout">
          <conversionPattern value="%property{MethodName}"/>
        </layout>
      </parameter>
    </appender>
    <root>
      <level value="ALL"/>
      <appender-ref ref="ADONetAppender_SqlServer"/>
    </root>
  </log4net>

3.第三步:

    如果是网站:

       MVC中在global.asax里面新增配置

       void Application_Start(object sender, EventArgs e)

           {

               // 在应用程序启动时运行的代码

               log4net.Config.XmlConfigurator.Configure();

           }

    如果是web项目和winform项目或者控制台项目:

    要在AssemblyInfo.cs 新增

    [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)] //当把东西写到web.config中时,改为web.config ----可以

    或者:[assembly: log4net.Config.XmlConfigurator()]  (把log4net的配置配置在web的配置文件时)

4.第四步:

  try
            {
                string a = "1a2b3c";
                int abc = Convert.ToInt32(a);
            }
            catch (Exception ex)
            {
                Admin.gigade.Log4NetCustom.LogMessage logMessage = new Admin.gigade.Log4NetCustom.LogMessage();
                logMessage.Content = string.Format("TargetSite:{0},Source:{1},Message:{2}", ex.TargetSite.Name, ex.Source, ex.Message);
                logMessage.MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                log.Error(logMessage);
            }

5.第五步

Log4NetCustom文件夹

CustomLayout.cs 类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using log4net.Util;
using System.IO;
using log4net.Layout.Pattern;
using System.Collections;
using log4net.Core;

namespace Admin.gigade.Log4NetCustom
{
    public class CustomLayout : log4net.Layout.PatternLayout
    {
        public CustomLayout()
        {
            this.AddConverter("property", typeof(MyMessagePatternConverter));
        }
    }
}

LogMessage.cs  类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Admin.gigade.Log4NetCustom
{
    public class LogMessage
    {
        private string m_MethodName;
        private string m_Content;
        public LogMessage()
        {
        }
        public LogMessage(string methodName, string content)
        {
            m_MethodName = methodName;
            m_Content = content;
        }
        public string MethodName
        {
            get
            {
                return m_MethodName;
            }
            set
            {
                m_MethodName = value;
            }
        }
        public string Content
        {
            get
            {
                return m_Content;
            }
            set
            {
                m_Content = value;
            }
        }
    }
}

MyMessagePatternConverter.cs 类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using log4net.Layout.Pattern;
using System.IO;
using log4net.Core;

namespace Admin.gigade.Log4NetCustom
{
    public class MyMessagePatternConverter : PatternLayoutConverter
    {
        protected override void Convert(System.IO.TextWriter writer, log4net.Core.LoggingEvent loggingEvent)
        {
            if (Option != null)
            {
                // Write the value for the specified key
                WriteObject(writer, loggingEvent.Repository, LookupProperty(Option, loggingEvent));
            }
            else
            {
                // Write all the key value pairs
                WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties());
            }
            //if (Option != null)
            //{
            //    // Write the value for the specified key
            //    WriteObject(writer, loggingEvent.Repository, loggingEvent.LookupProperty(Option));
            //}
            //else
            //{
            //    // Write all the key value pairs
            //    WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties());
            //}
        }
        /// <summary>
        /// 通q过反I射g获取Lu传入J的o日e志屠对象H的o某Y个属性E的o值E
        /// </summary>
        /// <param name="property"></param>
        /// <returns></returns>
        private object LookupProperty(string property, log4net.Core.LoggingEvent loggingEvent)
        {
            object propertyValue = string.Empty;
            System.Reflection.PropertyInfo propertyInfo = loggingEvent.MessageObject.GetType().GetProperty(property);
            if (propertyInfo != null)
                propertyValue = propertyInfo.GetValue(loggingEvent.MessageObject, null);
            return propertyValue;
        }
    }
}

OK了.

 

log4net配置

标签:

原文地址:http://www.cnblogs.com/sdya/p/4242397.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!