log4net的配置和使用

reference
http://www.cnblogs.com/wangchunlan2004/archive/2006/08/10/473400.html

在Assembly.cs中加入这样一句

[assembly: log4net.Config.DOMConfigurator()]//具体的参看引用

在web.config中添加如下项:

<configSections>//必须是configuration下的第一项目
  <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,

            log4net" />
 </configSections>
 <log4net>
  <root>
   <level value="DEBUG" />
   <appender-ref ref="LogFileAppender" />
   <appender-ref ref="ConsoleAppender" />
  </root>
  <logger name="testApp.Logging">
   <level value="DEBUG" />
  </logger>
  <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
   <param name="File" value="log-file.txt" />
   <param name="AppendToFile" value="true" />
   <layout type="log4net.Layout.PatternLayout">
    <param name="Header" value="[Header]/r/n" />
    <param name="Footer" value="[Footer]/r/n" />
    <param name="ConversionPattern" value="%d [%t] %-5p %c [%x]  - %m%n" />
    <!--2006-10-26 13:15:05,356 [2664] DEBUG defaultapp []  - u click the button 1.-->
   </layout>
   <filter type="log4net.Filter.LevelRangeFilter">
    <param name="LevelMin" value="DEBUG" />
    <param name="LevelMax" value="WARN" />
   </filter>
  </appender>
  <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
   <layout type="log4net.Layout.PatternLayout">
    <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />
   </layout>
  </appender>
 </log4net> 

新建一个类LoggerPage,要记录日志的窗体都可以继承该类,这是针对整个web站点的,
针对单个页面的,可以在LoggerPage添加一个log4net.spi.Level类当字段,并且把ilog的修饰符static去掉,使用log4net.spi.Level来对ilog进行设置

using System;
using System.Web;
using System.Reflection;
using log4net.Config;
using System.Web.UI;

namespace NewWebTest
{
 /// <summary>
 /// DebugPage 的摘要说明。
 /// </summary>
 public class LoggerPage:System.Web.UI.Page
 {
  protected static  readonly log4net.ILog ilog=log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);//这个反射在static下没有意义

  protected void DebugLog(object msg)
  {
   if(ilog.IsDebugEnabled)//提高效率

   {
    ilog.Debug(this.Combine(msg));
    //ilog.Debug(msg);
   }
  }

  private object Combine(object msg)
  {
   //object str=
            return this.GetType().Name+"-->"+msg.ToString();;
  }

  protected void ErrorLog(object msg)

//由于System.Web.UI.TemplateControl.Error()的存在 所以加了Log而不写New。
  {
   if(ilog.IsErrorEnabled)
   {
    ilog.Error(this.Combine(msg));
   }
  }

  protected void WarnLog(object msg)
  {
   if(ilog.IsWarnEnabled)
   {
    ilog.Warn(this.Combine(msg));
   }
  }

  protected void InfoLog(object msg)
  {
   if(ilog.IsInfoEnabled)
   {
    ilog.Info(this.Combine(msg));
   }
  }

  protected void FatalLog(object msg)
  {
   if(ilog.IsFatalEnabled)
   {
    ilog.Fatal(this.Combine(msg));
   }
  }

 

  }}

相关文章
相关标签/搜索