log4net配置

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了.

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。