首页 > 代码库 > Log4net

Log4net

http://www.cnblogs.com/jiajinyi/p/5884930.html

1、添加数据库引用

2、修改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>  <!--<log4net>    --><!-- Define some output appenders --><!--    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">      <file value="http://www.mamicode.com/test.txt"/>      <appendToFile value="http://www.mamicode.com/true"/>      <maxSizeRollBackups value="http://www.mamicode.com/10"/>      <maximumFileSize value="http://www.mamicode.com/1024KB"/>      <rollingStyle value="http://www.mamicode.com/Size"/>      <staticLogFileName value="http://www.mamicode.com/true"/>      <layout type="log4net.Layout.PatternLayout">        <conversionPattern value="http://www.mamicode.com/%date [%thread] %-5level %logger - %message%newline"/>      </layout>    </appender>    <root>      <level value="http://www.mamicode.com/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="ERROR"/>      <appender-ref ref="SysAppender"/>    </root>    <!-- Print only messages of level DEBUG or above in the packages -->    <logger name="WebLogger">      <level value="ERROR"/>    </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;" />      <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配置结束-->  <spring><!--spring.Net配置-->    <context>      <resource uri="file://~/Config/controllers.xml"/>      <resource uri="file://~/Config/service.xml"/>    </context>  </spring>  <connectionStrings>    <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-CZBK.ItcastOA.WebApp-20141209091941;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-CZBK.ItcastOA.WebApp-20141209091941.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=.\SQLEXPRESS;initial catalog=OA;user id=sa; password=ecollab;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="DalAssemblyPath" value="CZBK.ItcastOA.DAL"/>    <add key="NameSpace" value="CZBK.ItcastOA.DAL"/>  </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

3、注册

public class MvcApplication : SpringMvcApplication //System.Web.HttpApplication
{
protected void Application_Start()
{
log4net.Config.XmlConfigurator.Configure();//读取Log4Net配置信息

4、输出异常信息

技术分享
using CZBK.ItcastOA.WebApp.Models;using log4net;using Spring.Web.Mvc;using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Threading;using System.Web;using System.Web.Http;using System.Web.Mvc;using System.Web.Optimization;using System.Web.Routing;namespace CZBK.ItcastOA.WebApp{    // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明,    // 请访问 http://go.microsoft.com/?LinkId=9394801    public class MvcApplication : SpringMvcApplication //System.Web.HttpApplication    {        protected void Application_Start()        {            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/");            //WaitCallback            ThreadPool.QueueUserWorkItem((a) =>            {                while (true)                {                    if (MyExceptionAttribute.ExceptionQueue.Count > 0)                    {                       Exception ex= MyExceptionAttribute.ExceptionQueue.Dequeue();//出队                       //string fileName = DateTime.Now.ToString("yyyy-MM-dd")+".txt";                       //File.AppendAllText(fileLogPath + fileName, ex.ToString(), System.Text.Encoding.Default);                       ILog logger = LogManager.GetLogger("errorMsg");                       logger.Error(ex.ToString());                    }                    else                    {                        Thread.Sleep(3000);//如果队列中没有数据,休息避免造成CPU的空转.                    }                }            },fileLogPath);        }    }}
View Code

 

Log4net