Logging - MVC Using Log4net Save to File and Database

第一步:创建Config文件夹和log4net.config

第二步:在log4net.confg黏贴以下配置

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4Net" />
  </configSections>
  <!--日志的配置开始-->
  <log4net debug="true">
    <root>
      <level value="ALL" />
      <appender-ref ref="SysAppender" />
      <appender-ref ref="AdoNetAppender" />
    </root>

    <logger name="WebLogger">
      <level value="DEBUG" />
    </logger>

    <appender name="SysAppender" type="log4net.Appender.RollingFileAppender,log4net">
      <param name="File" value="App_Data/" />
      <param name="AppendToFile" value="true" />
      <param name="RollingStyle" value="Date" />
      <param name="DatePattern" value="&quot;Logs_&quot;yyyyMMdd&quot;.htm&quot;" />
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="&lt;HR COLOR=red&gt;%n异常时间:%d [%t] &lt;BR&gt;%n异常级别:%-5p &lt;BR&gt;%n异 常 类:%c [%x] &lt;BR&gt;%n%m &lt;BR&gt;%n &lt;HR Size=1&gt;" />
      </layout>
    </appender>
    <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
      <bufferSize value="1" />
      <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      <connectionString value="Data Source=.\sqlExpress;Initial Catalog=DB_Test;Integrated Security=False;User ID=sa;Password=P@ssword;Connect Timeout=15;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" providerName="System.Data.SqlClient" />
      <commandText value="INSERT INTO [DB_Test].[dbo].[TestSysLog] (Date, Thread, Level, Logger, Method, Location,Message, Exception) VALUES (@Date, @Thread, @Level, @Logger, @Method,@Location,@Message, @Exception)" />
      <parameter>
        <parameterName value="@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="@Level" />
        <dbType value="String" />
        <size value="255" />
        <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="@Method" />
        <dbType value="String" />
        <size value="255" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%method" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@Location" />
        <dbType value="String" />
        <size value="1023" />
        <layout type="log4net.Layout.PatternLayout" >
          <conversionPattern value="%location" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@Message" />
        <dbType value="String" />
        <size value="4000" />
        <layout type="log4net.Layout.PatternLayout">
          <conversionPattern value="%message" />
        </layout>
      </parameter>
      <parameter>
        <parameterName value="@Exception" />
        <dbType value="String" />
        <size value="8000" />
        <layout type="log4net.Layout.ExceptionLayout" />
      </parameter>
    </appender>
  </log4net>
  <!--日志的配置结束-->
</configuration>

第三步:配置AssemblyInfo.cs或Global.asax

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

或者

Application_Start()中加入

log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo("config\\log4net.config"));

第四步:添加自定义过滤器

public class MyExceptionFileAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            base.OnException(filterContext);
            LogHelper.WriteLog(filterContext.Exception.ToString());
        }
    }

第五步:添加类LogHelper

public class LogHelper
    {
        public static void WriteLog(string txt)
        {
            log4net.ILog log = log4net.LogManager.GetLogger("log4netlogger");
            log.Error(txt);

        }
    }

第六步:注册过滤器

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
      filters.Add(new HandleErrorAttribute());

      filters.Add(new MyExceptionFileAttribute());
}

最后:

在数据库端建立好相应的table,这样在表中就能看到记录的log,此文章中log文件在App_Data中。

posted @ 2017-02-23 15:28  Javi  阅读(333)  评论(0编辑  收藏  举报