利用log4net记录操作日志

1,目的:将用户操作日志写入sql server 数据库中

2,实现步骤:

  一,下载log4net.dll (推荐从官网下载 http://logging.apache.org/log4net/download_log4net.cgi

  二,在项目中引用 log4net.dll

  三,添加一个配置文件:我这里命名为 log4net.config(也可以在web.config里面配置为便于管理故新建了一个配置文件)

View Code
<?xml version="1.0"?>
<configuration>
  <configSections>
    <section   name= "log4net" type= "log4net.Config.Log4NetConfigurationSectionHandler,   log4net "   />
  </configSections>
  <log4net>
    <logger name="iNotes">
      <level value="INFO"/>
      <appender-ref ref="ADONetAppender" />
    </logger>
    <appender name="ADONetAppender" type="log4net.Appender.ADONetAppender">
      <bufferSize value="1" /><!--这里是表示是记录1 条到缓冲区,满1条后再写入SQL server 可根据需要自定义配置-->
      <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      <connectionString value="server=.;database=106_16_Driving;uid=sa;pwd=cx2012;" />
      <commandText value="INSERT INTO OperateLog ([OperateType],[Describe],[Userid],[OperateTime]) VALUES (@OperateType, @Describe, @Userid, @OperateTime)" />
      <parameter>
        <parameterName value="@OperateType" />
        <dbType value="String" />
        <size value="1" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%X{OperateType}" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@Describe" />
        <dbType value="String" />
        <size value="500" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%X{Describe}" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@Userid" />
        <dbType value="String" />
        <size value="20" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%X{Userid}" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@OperateTime" />
        <dbType value="String" />
        <size value="20" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%X{OperateTime}" />
        </layout>
      </parameter>
    </appender>
  </log4net>
</configuration>

 

  四,在项目的 AssemblyInfo.cs 文件的指定log4net 的配置文件路径

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

五,自定义记录函数

View Code
  public static void Operate_Log(string operateType, string describe)
        {
            log4net.ILog logToSQL = log4net.LogManager.GetLogger("iNotes");
            log4net.MDC.Set("OperateType", operateType);
            log4net.MDC.Set("Describe", describe);
            log4net.MDC.Set("Userid", HttpContext.Current.Session["userid"].ToString());
            log4net.MDC.Set("OperateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            logToSQL.Info("");
        }

 

六,在 后台代码中的调用

Operate_Log("1", "学员:" + txtName.Text);

posted on 2012-05-16 12:13  justconnor  阅读(3631)  评论(2编辑  收藏