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=""Logs_"yyyyMMdd".txt"" />
<!-- <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=" ----------------------header-------------------------- " />
<param name="Footer" value=" ----------------------footer-------------------------- " />
</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=""Logs_"yyyyMMdd".txt"" />
<!-- <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=" ----------------------header-------------------------- " />
<param name="Footer" value=" ----------------------footer-------------------------- " />
</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="data source=.;initial catalog=OA;user id=home;MultipleActiveResultSets=True;App=EntityFramework"" 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>
<?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] "/>
<footer value="[Footer] "/>
<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".log""/>
<staticLogFileName value="false"/>
<!--An alternate output encoding can be specified-->
<!-- <encoding value="unicodeFFFE" /> -->
<layout type="log4net.Layout.PatternLayout">
<header value="[Header] "/>
<footer value="[Footer] "/>
<conversionPattern value="%date [%thread] %-5level %logger [%ndc] <%property{auth}> - %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".log""/>
<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".log""/>
<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".log""/>
<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>
程序的最开始 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") > )
{
//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();
}
}
else
{
Thread.Sleep();//如果队列中没有数据,让当前线程休息,避免造成CUP空转.
}
} }, fileLogPath);
}
}
}
demo 源码:
https://gitee.com/xiaoshi657/XmlDemo/tree/master/Log4NetDemo
log4net 入门教程的更多相关文章
- ABP(现代ASP.NET样板开发框架)系列之2、ABP入门教程
点这里进入ABP系列文章总目录 基于DDD的现代ASP.NET开发框架--ABP系列之2.ABP入门教程 ABP是“ASP.NET Boilerplate Project (ASP.NET样板项目)” ...
- 基于DDD的现代ASP.NET开发框架--ABP系列之2、ABP入门教程
基于DDD的现代ASP.NET开发框架--ABP系列之2.ABP入门教程 ABP是“ASP.NET Boilerplate Project (ASP.NET样板项目)”的简称. ASP.NET Boi ...
- ABP入门教程
ABP入门教程 ABP是“ASP.NET Boilerplate Project (ASP.NET样板项目)”的简称. ASP.NET Boilerplate是一个用最佳实践和流行技术开发现代WEB应 ...
- ABP入门教程1 - 开篇
点这里进入ABP入门教程目录 基于DDD的现代ASP.NET开发框架 - ABP ABP是“ASP.NET Boilerplate Project (ASP.NET样板项目)”的简称. ASP.NET ...
- abp学习(四)——根据入门教程(aspnetMVC Web API进一步学习)
Introduction With AspNet MVC Web API EntityFramework and AngularJS 地址:https://aspnetboilerplate.com/ ...
- wepack+sass+vue 入门教程(三)
十一.安装sass文件转换为css需要的相关依赖包 npm install --save-dev sass-loader style-loader css-loader loader的作用是辅助web ...
- wepack+sass+vue 入门教程(二)
六.新建webpack配置文件 webpack.config.js 文件整体框架内容如下,后续会详细说明每个配置项的配置 webpack.config.js直接放在项目demo目录下 module.e ...
- wepack+sass+vue 入门教程(一)
一.安装node.js node.js是基础,必须先安装.而且最新版的node.js,已经集成了npm. 下载地址 node安装,一路按默认即可. 二.全局安装webpack npm install ...
- Content Security Policy 入门教程
阮一峰文章:Content Security Policy 入门教程
随机推荐
- Foundations of Qt Development 学习笔记 Part1 Tips1-50
1. 信号函数调用的时候仅仅会发送出信号,所以不需要执行 ,所以对于信号声明就行,但是不需要进行定义. 2. 只有槽函数可以声明为public,private,或者是protected的,而信号不行. ...
- Week2《Java程序设计》第二周学习总结
Week02-Java学习笔记2 1. 本周学习总结 本周学习了java的基本语法与类库,其中介绍了基本数据类型和引用类型,介绍了String类,String对象的拼接以及String的一些常用方法: ...
- 将从mysql数据库查询的信息,遍历到List<>以及一些随机数的生成
将从mysql数据库查询的信息,遍历到List<>以及一些随机数的生成. 代码比较乱,但是方法还是对的,大家又需要的选择看,希望对博友 有帮助,欢迎留言分享! public class s ...
- Qt之格栅布局(QGridLayout)
简述 QGridLayout:格栅布局,也被称作网格布局(多行多列). 栅格布局将位于其中的窗口部件放入一个网状的栅格之中.QGridLayout需要将提供给它的空间划分成的行和列,并把每个窗口部件插 ...
- C++抽象类的实现
1.什么是抽象类? 答:简单的说,抽象类就是至少有一个纯虚函数的类. 2.抽象类的作用? 答:抽象类的主要作用就是为它所组织的继承层次结构提供一个公共的基类,这样它就具有公有行为的特征,其它派生的类可 ...
- Unity的Update() 和 FixedUpdate()的区别
Update() 和 FixedUpdate()在游戏中都会在更新的时候自动循环调用. 但是Update是在每次渲染新的一帧的时候才会调用,也就是说,这个函数的更新频率和设备的性能有关以及被渲染的物体 ...
- Qt TabWidget QTabBar 宽高设置
/*************************************************************************** * Qt TabWidget QTabBar ...
- terminal小工具
计算器 >bc >quit 显示日历 >cal
- 使用python对文件中的数值进行累加
问题描述: 一个文件由若干条记录组成,记录的格式为:“num1 num2”,有时候,需要统计文件中num1对应的num2的总值.处理问题的思路 用传说中的python来处理,很方便.几行代码就可以了. ...
- HihoCoder1621 : 超市规划(四边形DP优化)()
超市规划 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 小Hi居住的城市的中轴线恰好是一条马路.沿着这条马路一共坐落有N个居民小区,其中第i个小区距离马路一端的距离是A ...