log4net 入门教程

 

1、下载dll

下载地址:http://mirror.reverse.net/pub/apache/logging/log4net/binaries/

github:https://github.com/apache/logging-log4net

2、添加引用

添加log4net.dll的引用(bin\net\2.0\release  不能引用debug版本  不一定是2.0,找对应的net版本)

3、修改配置文件

在web.Config(或app.Config)添加配置,见下文 

配置分两步:

1.

<------放到<configuration>字节下的<configSections>字节下--------->
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>

2.

<!--log4net配置-->
<------放到<configuration>字节下--------->
  <log4net>
    <!-- OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL -->
    <!-- Set root logger level to ERROR and its appenders -->
    <root>
      <level value="WARN"/>
      <appender-ref ref="SysAppender"/>
    </root>

    <!-- Print only messages of level DEBUG or above in the packages -->
    <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;.txt&quot;" />
      <!--  <ConversionPattern value="记录时间:%date 线程ID:[%thread] 日志级别:%-5level 出错类:%logger property:[%property{NDC}] - 错误描述:%message%newline"  />-->
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
        <param name="Header" value="&#13;&#10;----------------------header--------------------------&#13;&#10;" />
        <param name="Footer" value="&#13;&#10;----------------------footer--------------------------&#13;&#10;" />
      </layout>
    </appender>
    <appender name="consoleApp" type="log4net.Appender.ConsoleAppender,log4net">
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
      </layout>
    </appender>
  </log4net>
  
  <!--log4net配置结束-->

4、初始化:

在程序最开始加入log4net.Config.XmlConfigurator.Configure();不要加入页面的load

5、调用:

ILog logger = LogManager.GetLogger("errorMsg");

logger.Error(errorMsg);//将异常信息写到磁盘上.

 

实例代码:

web.Config

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=152368
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <sectionGroup name="spring"><!--Spring.Net配置-->
      <section name="context" type="Spring.Context.Support.MvcContextHandler, Spring.Web.Mvc4"/>
    </sectionGroup>
    <!--Log4Net配置-->
      <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>
  <spring><!--Spring.Net配置-->
    <context>
      <resource uri="file://~/Config/controllers.xml"/>
      <resource uri="file://~/Config/service.xml"/>
    </context>
  </spring>
  <!--Spring.Net配置结束-->
<!--log4net配置-->
  <!--<log4net>
    --><!-- Define some output appenders --><!--
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="test.txt"/>
      <appendToFile value="true"/>
      <maxSizeRollBackups value="10"/>
      <maximumFileSize value="1024KB"/>
      <rollingStyle value="Size"/>
      <staticLogFileName value="true"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
        
      </layout>
    </appender>
    <root>
      <level value="DEBUG"/>
      <appender-ref ref="RollingLogFileAppender"/>
    </root>
  </log4net>-->
  <log4net>
    <!-- OFF, FATAL, ERROR, WARN, INFO, DEBUG, ALL -->
    <!-- Set root logger level to ERROR and its appenders -->
    <root>
      <level value="WARN"/>
      <appender-ref ref="SysAppender"/>
    </root>

    <!-- Print only messages of level DEBUG or above in the packages -->
    <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;.txt&quot;" />
      <!--  <ConversionPattern value="记录时间:%date 线程ID:[%thread] 日志级别:%-5level 出错类:%logger property:[%property{NDC}] - 错误描述:%message%newline"  />-->
      <param name="StaticLogFileName" value="false" />
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
        <param name="Header" value="&#13;&#10;----------------------header--------------------------&#13;&#10;" />
        <param name="Footer" value="&#13;&#10;----------------------footer--------------------------&#13;&#10;" />
      </layout>
    </appender>
    <appender name="consoleApp" type="log4net.Appender.ConsoleAppender,log4net">
      <layout type="log4net.Layout.PatternLayout,log4net">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
      </layout>
    </appender>
  </log4net>
  
  <!--log4net配置结束-->
  <connectionStrings>
    <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-CZBK.HeiMaOA.WebApp-20140915093444;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-CZBK.HeiMaOA.WebApp-20140915093444.mdf" />
    <add name="OAEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.;initial catalog=OA;user id=home;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
 
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <!--命名空间与程序集名称配置-->
    <add key="DalNameSpace" value="CZBK.HeiMaOA.DAL"/>
    <add key="DalAssembly" value="CZBK.HeiMaOA.DAL"/>
    <!--命名空间与程序集名称配置结束-->
    
    <!--Workflow持久化数据库链接字符串-->
    <add key="workflowConnection" value="server=.;uid=home;pwd=;database=OA"/>
  </appSettings>
  <system.web>
    <httpRuntime targetFramework="4.5" />
    <compilation debug="true" targetFramework="4.5" />
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" />
    </authentication>
    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages" />
      </namespaces>
    </pages>
    <profile defaultProvider="DefaultProfileProvider">
      <providers>
        <add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
      </providers>
    </profile>
    <membership defaultProvider="DefaultMembershipProvider">
      <providers>
        <add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
      </providers>
    </membership>
    <roleManager defaultProvider="DefaultRoleProvider">
      <providers>
        <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
      </providers>
    </roleManager>
    <!--
            If you are deploying to a cloud environment that has multiple web server instances,
            you should change session state mode from "InProc" to "Custom". In addition,
            change the connection string named "DefaultConnection" to connect to an instance
            of SQL Server (including SQL Azure and SQL  Compact) instead of to SQL Server Express.
      -->
    <sessionState mode="InProc" customProvider="DefaultSessionProvider">
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
      </providers>
    </sessionState>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
      <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
  </entityFramework>
</configuration>
View Code

 

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
    </configSections>
    <log4net  debug="true">
        <!--Define   some   output   appenders   -->
        <appender   name="RollingLogFileAppender"   type="log4net.Appender.RollingFileAppender">
            <threshold   value="INFO"/>
            <file   value="D:\[Publish_log]\SNS_Test\RollingLog.log"/>
            <appendToFile   value="true"/>
            <maxSizeRollBackups   value="10"/>
            <maximumFileSize   value="100"/>
            <rollingStyle   value="Size"/>
            <staticLogFileName   value="true"/>
            <layout   type="log4net.Layout.PatternLayout">
                <header   value="[Header]&#xA;"/>
                <footer   value="[Footer]&#xA;"/>
                <conversionPattern   value="%date   [%thread]   %-5level   %logger   [%ndc]   -   %message%newline"/>
            </layout>
        </appender>
        <appender   name="LogFileAppender"   type="log4net.Appender.RollingFileAppender">
            <threshold   value="ALL"/>
            <file   value="D:\[Publish_log]\SNS_Test\Debug"/>
            <!--Example   using   environment   variables   in   params-->
            <!-- <file   value="${TMP}\log-file.txt"   /> -->
            <appendToFile   value="true"/>
            <rollingStyle   value="Date"/>
            <DatePattern   value="yyyy-MM-dd&quot;.log&quot;"/>
            <staticLogFileName   value="false"/>
            <!--An   alternate   output   encoding   can   be   specified-->
            <!-- <encoding   value="unicodeFFFE"   /> -->
            <layout   type="log4net.Layout.PatternLayout">
                <header   value="[Header]&#xA;"/>
                <footer   value="[Footer]&#xA;"/>
                <conversionPattern   value="%date   [%thread]   %-5level   %logger   [%ndc]   &lt;%property{auth}&gt;   -   %message%newline"/>
            </layout>
            <filter type="log4net.Filter.LevelRangeFilter">
                <param name="LevelMin" value="INFO" />
                <param name="LevelMax" value="FATAL" />
            </filter>
        </appender>
        <!--messages   in   emails-->
        <appender   name="SmtpAppender"   type="log4net.Appender.SmtpAppender">
            <threshold   value="FATAL"/>
            <layout   type="log4net.Layout.PatternLayout"   value="%date   [%thread]   %-5level   %logger   -   %message%newline"/>
            <subject   value="%-5level   %logger"/>
            <to   value="william@sina.com"/>
            <from   value="sdf@qq.com"/>
            <smtpHost   value="mail.qq.com"/>
        </appender>
        <appender   name="PortalMessageLogFileAppender"   type="log4net.Appender.RollingFileAppender">
            <threshold   value="ALL"/>
            <file   value="D:\[Publish_log]\SNS_Test\PortalMessageLog"/>
            <appendToFile   value="true"/>
            <rollingStyle   value="Date"/>
            <DatePattern   value="yyyy-MM-dd&quot;.log&quot;"/>
            <staticLogFileName   value="false"/>
            <!--An   alternate   output   encoding   can   be   specified-->
            <!-- <encoding   value="unicodeFFFE"   /> -->
            <layout   type="log4net.Layout.PatternLayout">
                <conversionPattern   value="%date  %-5level  -  %message%newline"/>
            </layout>
        </appender>
        <appender   name="CacheLogFileAppender"   type="log4net.Appender.RollingFileAppender">
            <threshold   value="ALL"/>
            <file   value="D:\[Publish_log]\SNS_Test\CacheLog"/>
            <appendToFile   value="true"/>
            <rollingStyle   value="Date"/>
            <DatePattern   value="yyyy-MM-dd&quot;.log&quot;"/>
            <staticLogFileName   value="false"/>
            <!--An   alternate   output   encoding   can   be   specified-->
            <!-- <encoding   value="unicodeFFFE"   /> -->
            <layout   type="log4net.Layout.PatternLayout">
                <conversionPattern   value="%date  %-5level  -  %message%newline"/>
            </layout>
        </appender>
        <appender   name="MessageMonitorLogFileAppender"   type="log4net.Appender.RollingFileAppender">
            <threshold   value="ALL"/>
            <file   value="D:\[Publish_log]\SNS_Test\MessageMonitorLog"/>
            <appendToFile   value="true"/>
            <rollingStyle   value="Date"/>
            <DatePattern   value="yyyy-MM-dd&quot;.log&quot;"/>
            <staticLogFileName   value="false"/>
            <!--An   alternate   output   encoding   can   be   specified-->
            <!-- <encoding   value="unicodeFFFE"   /> -->
            <layout   type="log4net.Layout.PatternLayout">
                <conversionPattern   value="%date  %-5level  -  %message%newline"/>
            </layout>
        </appender>
        <!--   Setup   the   root   category,   add   the   appenders   and   set   the   default   level   -->
        <root>
            <level   value="ALL"/>
            <appender-ref   ref="LogFileAppender"/>
            <!-- <appender-ref   ref="ConsoleAppender"   /> -->
            <!--   <appender-ref   ref="ADONetAppender_SqlServer"   />   -->
            <!--   <appender-ref   ref="NetSendAppender"   />   -->
            <appender-ref   ref="SmtpAppender"/>
            <!-- <appender-ref   ref="RollingLogFileAppender"   /> -->
        </root>
        <logger name="PortalMessageLog" additivity="false">
            <level value="ALL"/>
            <appender-ref   ref="PortalMessageLogFileAppender"/>
        </logger>
        <logger name="CacheLog" additivity="false">
            <level value="ALL"/>
            <appender-ref   ref="CacheLogFileAppender"/>
        </logger>
        <logger name="MessageMonitorLog" additivity="false">
            <level value="ALL"/>
            <appender-ref   ref="MessageMonitorLogFileAppender"/>
        </logger>
    </log4net>
</configuration>
View Code

 

程序的最开始 Global.asax.cs

using CZBK.HeiMaOA.WebApp.Models;
using log4net;
using Spring.Web.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace CZBK.HeiMaOA.WebApp
{
    // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明,
    // 请访问 http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : SpringMvcApplication//System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            IndexManager.GetInstance().CreateThread();//开启线程,扫描队列获取图书的信息写到Lucene.Net中。
            log4net.Config.XmlConfigurator.Configure();//读取Log4Net配置信息
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            string fileLogPath = Server.MapPath("/Log/");//指定用来保存错误日志文件的文件夹路径.

        
            //开启一个线程扫描日志队列
            ThreadPool.QueueUserWorkItem((a) =>
            {
                while (true)//不断扫描日志队列.
                {
                    //  if (MyExceptionAttribute.exceptionQueue.Count() > 0)//判断队列中是否有数据
                    if (MyExceptionAttribute.redisClent.GetListCount("errorMsg") > 0)
                    {
                        //Exception ex= MyExceptionAttribute.exceptionQueue.Dequeue();//出队,
                        string errorMsg = MyExceptionAttribute.redisClent.DequeueItemFromList("errorMsg");
                        if (!string.IsNullOrEmpty(errorMsg))
                        {
                            string fileName = DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                            File.AppendAllText(fileLogPath + fileName, ex.ToString(), Encoding.Default);//将异常写到文件中。异常信息写到磁盘上.
                        }
                        else
                        {
                            Thread.Sleep(3000);
                        }
                    }
                    else
                    {
                        Thread.Sleep(3000);//如果队列中没有数据,让当前线程休息,避免造成CUP空转.
                    }
                }


            }, fileLogPath);
        }
    }
}
View Code

 

demo 源码:

https://gitee.com/xiaoshi657/XmlDemo/tree/master/Log4NetDemo

posted @ 2015-07-29 23:48  xiaoshi657  阅读(503)  评论(0编辑  收藏  举报