首页 > 代码库 > 关于使用Log4Net将日志插入oracle数据库中

关于使用Log4Net将日志插入oracle数据库中

1.关于配置文件。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section   name="log4net"   type="System.Configuration.IgnoreSectionHandler"   />
  </configSections>
  <log4net>
    <root>
      <level value="http://www.mamicode.com/ALL" />
      <appender-ref ref="rollingFile" />
      <appender-ref ref="ADONetAppender"/>
    </root>
    <logger name="Presin_log">
      <level value="http://www.mamicode.com/ALL" />
      <appender-ref ref="PresinLoging" />
    </logger>
    <logger name="Oracle_DB">
      <level value="http://www.mamicode.com/ALL" />
      <appender-ref ref="OracleDB" />
    </logger>
    <logger name="flowseting_log">
      <level value="http://www.mamicode.com/ALL" />
      <appender-ref ref="flowsetingLoging" />
    </logger>
    <!--Presin日志-->
    <appender name="PresinLoging" type="log4net.Appender.RollingFileAppender,log4net" >
      <param name="File" value="http://www.mamicode.com/Log/Presin/" />
      <param name="AppendToFile" value="http://www.mamicode.com/true" />
      <param name="RollingStyle" value="http://www.mamicode.com/Composite" />
      <param name="DatePattern" value="http://www.mamicode.com/yyyy-MM-dd.‘.txt‘" />
      <param name="MaximumFileSize" value ="http://www.mamicode.com/5MB"/>
      <param name="StaticLogFileName" value="http://www.mamicode.com/false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <conversionPattern value="http://www.mamicode.com/%date %-5level %newline %logger - %message%newline %newline" />
      </layout>
    </appender>
    <appender name="OracleDB" type="log4net.Appender.AdoNetAppender,log4net" >
      <bufferSize value="http://www.mamicode.com/20"/>
      <connectionType value="http://www.mamicode.com/System.Data.OracleClient.OracleConnection, System.Data.OracleClient, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
      <connectionString value="http://www.mamicode.com/Data Source=ORCl;User ID=sa;Password=sa;" />
      <commandText value="http://www.mamicode.com/INSERT INTO LogDetails (LogDate,loglevel,loglogger,LogMessage,logfunctionname,logbusinessname) VALUES (:log_date,:log_level,:logger,:message,:FunctionName,:BusinessName)" />
      <parameter>
        <parameterName value="http://www.mamicode.com/:log_date" />
        <dbType value="http://www.mamicode.com/DateTime" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="http://www.mamicode.com/%date{yyyy-MM-dd HH:mm:ss}" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="http://www.mamicode.com/:log_level" />
        <dbType value="http://www.mamicode.com/String" />
        <size value="http://www.mamicode.com/200" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="http://www.mamicode.com/%p" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="http://www.mamicode.com/:logger" />
        <dbType value="http://www.mamicode.com/String" />
        <size value="http://www.mamicode.com/200" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="http://www.mamicode.com/%logger" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="http://www.mamicode.com/:message" />
        <dbType value="http://www.mamicode.com/String" />
        <size value="http://www.mamicode.com/2000" />
        <layout type="MapgisEgovLog4_WriteLog.MyLayout">
          <conversionPattern value="http://www.mamicode.com/%property{Message}" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="http://www.mamicode.com/:FunctionName" />
        <dbType value="http://www.mamicode.com/String" />
        <size value="http://www.mamicode.com/200" />
        <layout type="MapgisEgovLog4_WriteLog.MyLayout">
          <conversionPattern value="http://www.mamicode.com/%property{FunctionName}" />
        </layout>
      </parameter>
    <parameter>
        <parameterName value="http://www.mamicode.com/:BusinessName" />
        <dbType value="http://www.mamicode.com/String" />
        <size value="http://www.mamicode.com/200" />
        <layout type="MapgisEgovLog4_WriteLog.MyLayout">
          <conversionPattern value="http://www.mamicode.com/%property{BusinessName}" />
        </layout>
      </parameter>
    </appender>
    <!--flowseting日志-->
    <appender name="flowsetingLoging" type="log4net.Appender.RollingFileAppender,log4net" >
      <param name="File" value="http://www.mamicode.com/Log/flowseting/" />
      <param name="AppendToFile" value="http://www.mamicode.com/true" />
      <param name="RollingStyle" value="http://www.mamicode.com/Date" />
      <param name="DatePattern" value="http://www.mamicode.com/yyyyMMdd" />
      <param name="StaticLogFileName" value="http://www.mamicode.com/true" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <conversionPattern value="http://www.mamicode.com/%date %-5level %newline %logger - %message%newline %newline"  />
      </layout>
    </appender>
  </log4net>
</configuration>

 

a.在配置文件中,root节点下需要增加<appender-ref ref="ADONetAppender"/>代表允许将日志插入数据库中。
<root>
      <level value="http://www.mamicode.com/ALL" />
      <appender-ref ref="rollingFile" />
      <appender-ref ref="ADONetAppender"/>
    </root>

 

技术分享
rollingFile是将日志写入文件中,在这里不做讨论。
ADONetAppender是将日志写入数据库中,然后log4Net会根据接下来的配置connectionType和connectionString判断插入何种数据库和哪个数据库
b.增加一个logname,方便进一步添加属性
<logger name="Oracle_DB">
      <level value="http://www.mamicode.com/ALL" />
      <appender-ref ref="OracleDB" />
 </logger>

 

技术分享
c.进一步配置OracleDB
<appender name="OracleDB" type="log4net.Appender.AdoNetAppender,log4net" >
      <bufferSize value="http://www.mamicode.com/20"/>
      <connectionType value="http://www.mamicode.com/System.Data.OracleClient.OracleConnection, System.Data.OracleClient, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
      <connectionString value="http://www.mamicode.com/Data Source=ORCl;User ID=sa;Password=sa;" />
      <commandText value="http://www.mamicode.com/INSERT INTO LogDetails (LogDate,loglevel,loglogger,LogMessage,logfunctionname,logbusinessname) VALUES (:log_date,:log_level,:logger,:message,:FunctionName,:BusinessName)" />
      <parameter>
        <parameterName value="http://www.mamicode.com/:log_date" />
        <dbType value="http://www.mamicode.com/DateTime" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="http://www.mamicode.com/%date{yyyy-MM-dd HH:mm:ss}" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="http://www.mamicode.com/:log_level" />
        <dbType value="http://www.mamicode.com/String" />
        <size value="http://www.mamicode.com/200" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="http://www.mamicode.com/%p" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="http://www.mamicode.com/:logger" />
        <dbType value="http://www.mamicode.com/String" />
        <size value="http://www.mamicode.com/200" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="http://www.mamicode.com/%logger" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="http://www.mamicode.com/:message" />
        <dbType value="http://www.mamicode.com/String" />
        <size value="http://www.mamicode.com/2000" />
        <layout type="MapgisEgovLog4_WriteLog.MyLayout">
          <conversionPattern value="http://www.mamicode.com/%property{Message}" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="http://www.mamicode.com/:FunctionName" />
        <dbType value="http://www.mamicode.com/String" />
        <size value="http://www.mamicode.com/200" />
        <layout type="MapgisEgovLog4_WriteLog.MyLayout">
          <conversionPattern value="http://www.mamicode.com/%property{FunctionName}" />
        </layout>
      </parameter>
    <parameter>
        <parameterName value="http://www.mamicode.com/:BusinessName" />
        <dbType value="http://www.mamicode.com/String" />
        <size value="http://www.mamicode.com/200" />
        <layout type="MapgisEgovLog4_WriteLog.MyLayout">
          <conversionPattern value="http://www.mamicode.com/%property{BusinessName}" />
        </layout>
      </parameter>
    </appender>

 

技术分享
其中需要注意的是:
(1).bufferSize,代表缓存的记录条数,设置为20,表示log4net会在有20条日志时调用数据库并插入。
(2).connectionType代表数据库类型,注意Version和PublicKeyToken一定要于自己系统调用的版本一致。oracle的2.0版本的System.Data.OracleClient一般是2.0.0.0和b77a5c561934e089
(3)commandText代表插入的语句,注意oracle的参数是:参数,而sqlserver是@参数,且此处一定要保证,sql语句正确,如数据库中无此表或表无此字段,log4Net都不会报错,但不会进行任何操作。
(4)通过parameter逐一将要插入数据库的参数进行赋值和格式化
如:日期格式化和赋值
<parameter>
        <parameterName value="http://www.mamicode.com/:log_date" />
        <dbType value="http://www.mamicode.com/DateTime" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="http://www.mamicode.com/%date{yyyy-MM-dd HH:mm:ss}" />
        </layout>
</parameter>

 

技术分享
字符串默认格式化和赋值
      <parameter>
        <parameterName value="http://www.mamicode.com/:logger" />
        <dbType value="http://www.mamicode.com/String" />
        <size value="http://www.mamicode.com/200" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="http://www.mamicode.com/%logger" />
        </layout>
      </parameter>

 

技术分享
log4Net提供给我们的字段有:
log_date,log_level,logger,message等,其余的字段需要我们自定义
自定义字段格式化和赋值
      <parameter>
        <parameterName value="http://www.mamicode.com/:FunctionName" />
        <dbType value="http://www.mamicode.com/String" />
        <size value="http://www.mamicode.com/200" />
        <layout type="MapgisEgovLog4_WriteLog.MyLayout">
          <conversionPattern value="http://www.mamicode.com/%property{FunctionName}" />
        </layout>
      </parameter>

 

技术分享
log4Net提供的字段,我们也可以通过自定义重载
      <parameter>
        <parameterName value="http://www.mamicode.com/:message" />
        <dbType value="http://www.mamicode.com/String" />
        <size value="http://www.mamicode.com/2000" />
        <layout type="MapgisEgovLog4_WriteLog.MyLayout">
          <conversionPattern value="http://www.mamicode.com/%property{Message}" />
        </layout>
      </parameter>

 

技术分享
注意:layout Type中填写的是og4net的格式化类以及其命名空间。
conversionPattern中是使用扩展的格式化类中注册的格式化方法。
 
扩展格式化需要一些后台代码支持
 
/// <summary>  
    /// 包含了所有的自定字段属性  
    /// </summary>  
    public class LogContent
    {
        public LogContent(string sFunctionName, string sLogMessasge,string sLogBusinessName)
        {
            FunctionName = sFunctionName;
            Message = sLogMessasge;
            BusinessName = sLogBusinessName;
        }

        /// <summary>  
        /// 方法名称  
        /// </summary>  
        public string FunctionName { get; set; }

        /// <summary>  
        /// 日志描述信息  
        /// </summary>  
        public string Message { get; set; }

        /// <summary>
        /// 业务名称
        /// </summary>
        public string BusinessName { get; set; }
    }


    public class MyLayout : PatternLayout
    {
        public MyLayout()
        {
            this.AddConverter("property", typeof(LogInfoPatternConverter));
        }
    }

    public class LogInfoPatternConverter : PatternLayoutConverter
    {

        protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
        {
            if (Option != null)
            {
                WriteObject(writer, loggingEvent.Repository, LookupProperty(Option, loggingEvent));
            }
            else
            {
                WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties());
            }
        }
        /// <summary>  
        /// 通过反射获取传入的日志对象的某个属性的值  
        /// </summary>  
        /// <param name="property"></param>  
        /// <returns></returns>  

        private object LookupProperty(string property, log4net.Core.LoggingEvent loggingEvent)
        {
            object propertyValue = http://www.mamicode.com/string.Empty;
            PropertyInfo propertyInfo = loggingEvent.MessageObject.GetType().GetProperty(property);
            if (propertyInfo != null)
                propertyValue = propertyInfo.GetValue(loggingEvent.MessageObject, null);
            return propertyValue;
        }
    }
其中:
d.自定义字段的类
    public class LogContent
    {
        public LogContent(string sFunctionName, string sLogMessasge,string sLogBusinessName)
        {
            FunctionName = sFunctionName;
            Message = sLogMessasge;
            BusinessName = sLogBusinessName;
        }

        /// <summary>  
        /// 方法名称  
        /// </summary>  
        public string FunctionName { get; set; }

        /// <summary>  
        /// 日志描述信息  
        /// </summary>  
        public string Message { get; set; }

        /// <summary>
        /// 业务名称
        /// </summary>
        public string BusinessName { get; set; }
    }

 

技术分享
e.扩展log4net的格式化方法
public class MyLayout : PatternLayout
    {
        public MyLayout()
        {
            this.AddConverter("property", typeof(LogInfoPatternConverter));
        }
    }

 

技术分享
f.通过反射的方法获取LogContent中定义的字段
public class LogInfoPatternConverter : PatternLayoutConverter
    {

        protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
        {
            if (Option != null)
            {
                WriteObject(writer, loggingEvent.Repository, LookupProperty(Option, loggingEvent));
            }
            else
            {
                WriteDictionary(writer, loggingEvent.Repository, loggingEvent.GetProperties());
            }
        }
        /// <summary>  
        /// 通过反射获取传入的日志对象的某个属性的值  
        /// </summary>  
        /// <param name="property"></param>  
        /// <returns></returns>  

        private object LookupProperty(string property, log4net.Core.LoggingEvent loggingEvent)
        {
            object propertyValue = http://www.mamicode.com/string.Empty;
            PropertyInfo propertyInfo = loggingEvent.MessageObject.GetType().GetProperty(property);
            if (propertyInfo != null)
                propertyValue = propertyInfo.GetValue(loggingEvent.MessageObject, null);
            return propertyValue;
        }
    }

调用示例

log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(strPath + "配置文件.xml"));
 ILog log = LogManager.GetLogger("Oracle_DB");
log.Info(new LogContent("Button1_Click", "测试成功","测试"));

 

参考:

http://blog.csdn.net/kongwei521/article/details/52242319

 

 

关于使用Log4Net将日志插入oracle数据库中