Log4net配置方式
Web应用程序配置log4net(添加Log4net.dll):
1,修改web.config
1 <?xml version="1.0" encoding="utf-8"?> 2 3 <!-- 4 有关如何配置 ASP.NET 应用程序的详细消息,请访问 5 http://go.microsoft.com/fwlink/?LinkId=169433 6 --> 7 <configuration> 8 <configSections> 9 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> 10 </configSections> 11 <log4net> 12 <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender" > 13 <file value="log.txt"/> 14 <appendToFile value="true"/> 15 <maxSizeRollBackups value="10"/> 16 <maximumFileSize value="1024KB"/> 17 <rollingStyle value="Size"/> 18 <staticLogFileName value="true"/> 19 20 <layout type="log4net.Layout.PatternLayout"> 21 <conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message%newline" /> 22 </layout> 23 </appender> 24 <root> 25 <level value="DEBUG" /> 26 <appender-ref ref="RollingLogFileAppender" /> 27 </root> 28 </log4net> 29 <system.web> 30 <compilation debug="true" targetFramework="4.0" /> 31 </system.web> 32 </configuration>
2,在全局文件中添加:
protected void Application_Start(object sender, EventArgs e)
{
log4net.Config.XmlConfigurator.Configure();
}
3,应用:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using log4net; using System.Net; namespace Log4netTest { public partial class WebForm1 : System.Web.UI.Page { private static ILog log = LogManager.GetLogger(typeof(WebForm1)); protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { //ILog log = LogManager.GetLogger(typeof(WebForm1)); log.Debug("我擦啊!!!!!!!"); } protected void Button2_Click(object sender, EventArgs e) { log.Warn("警告一下哦!!"); } protected void Button3_Click(object sender, EventArgs e) { WebClient wc = new WebClient(); string data=""; //可处理的异常用try catch,未处理的异常在全局文件中捕获。 try { data= wc.DownloadString("http://www.youtube.com"); Response.Write("<font color=red>内容是:</font>"+data); } catch (Exception ex) { log.Error(ex.Message); Response.Write("打开失败啊!"); } } } }
4,处理未捕获到的异常(未try的)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using log4net;
namespace Log4netTest
{
public class Global : System.Web.HttpApplication
{
private static ILog log = LogManager.GetLogger(typeof(Global));
protected void Application_Start(object sender, EventArgs e)
{
log4net.Config.XmlConfigurator.Configure();
}
protected void Session_Start(object sender, EventArgs e)
{
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
//在这里处理未捕获的异常
log.Error("发生未处理异常!",HttpContext.Current.Error);
}
protected void Session_End(object sender, EventArgs e)
{
}
protected void Application_End(object sender, EventArgs e)
{
}
}
}