Log4Net 使用详细

 

一.添加程序程集Assembly

在使用log4Net类的namespace前加上:

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

namespace XX.Log.BLL

{

	//To do

}

如果是Asp.net应用程序

1. 在Properties/AssemblyInfo.cs文件中加上

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config" , Watch = true )] (独立配置文件)或

[assembly: log4net.Config.XmlConfigurator(Watch = true )] (配置在web.config文件中)

2.在Globall.cs的Application_Start中添加:

protected void Application_Start(object sender, EventArgs e)

        {

            log4net.Config.XmlConfigurator.Configure();

        }

log4net.Config.XmlConfigurator.Configure有重载,如果是独立配置文件可以使用重载

 

3.添加配置文件,以下是使用是精简的

<?xml version="1.0" encoding="utf-8"?>

<configuration>

  <configSections>

    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>

  </configSections>



  <log4net>

    <appender name="FileAppender" type="log4net.Appender.RollingFileAppender">

      <file value="" />

      <appendToFile value="true" />

      <param name="StaticLogFileName" value="false"/>
      <param name="DatePattern" value="yyyyMMdd&quot;_log-file.txt&quot;"/>
      <param name="RollingStyle" value="Date"/>
    <layout type="log4net.Layout.PatternLayout">

        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />

      </layout>

    </appender>





    <appender name="ADONetAppender" type="log4net.Appender.AdoNetAppender">

      <bufferSize value="50" />

      <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

      <connectionString value="data source=xxxx;initial catalog=xx;integrated security=false;persist security info=True;User ID=sa;Password=******" />

      <commandText value="INSERT INTO Logs ([LogTime],[AppCode],[LogLevel],[LogSource],[Message],[Description]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />

      <parameter>

        <parameterName value="@log_date" />

        <dbType value="DateTime" />

        <layout type="log4net.Layout.RawTimeStampLayout" />

      </parameter>

      <parameter>

        <parameterName value="@thread" />

        <dbType value="String" />

        <size value="255" />

        <layout type="log4net.Layout.PatternLayout">

          <conversionPattern value="%thread" />

        </layout>

      </parameter>

      <parameter>

        <parameterName value="@log_level" />

        <dbType value="String" />

        <size value="50" />

        <layout type="log4net.Layout.PatternLayout">

          <conversionPattern value="%level" />

        </layout>

      </parameter>

      <parameter>

        <parameterName value="@logger" />

        <dbType value="String" />

        <size value="255" />

        <layout type="log4net.Layout.PatternLayout">

          <conversionPattern value="%logger" />

        </layout>

      </parameter>

      <parameter>

        <parameterName value="@message" />

        <dbType value="String" />

        <size value="4000" />

        <layout type="log4net.Layout.PatternLayout">

          <conversionPattern value="%message" />

        </layout>

      </parameter>

      <parameter>

        <parameterName value="@exception" />

        <dbType value="String" />

        <size value="2000" />

        <layout type="log4net.Layout.ExceptionLayout" />

      </parameter>



    </appender>

    <!--定义日志的输出媒介,下面定义日志以四种方式输出。也可以下面的按照一种类型或其他类型输出。-->

    <root>

      <!--<level value="WARN"/>

      <level value="INFO"/>

      <level value="DEBUG"/>

      <level value="FINE"/>

      <appender-ref ref="ADONetAppender" />-->

    </root>



    <logger name="DBLogger">

      <level value="WARN"/>

      <level value="INFO"/>

      <level value="DEBUG"/>

      <level value="FINE"/>

      <appender-ref ref="ADONetAppender" />

    </logger>



    <logger name="FilelLoger">

      <level value="WARN"/>

      <level value="INFO"/>

      <level value="DEBUG"/>

      <level value="FINE"/>

      <appender-ref ref="FileAppender" />

    </logger>

  </log4net>



</configuration>

其中<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />可能会因为ADO版本不同会有所差异,Version=可能为1.0.0.3之类的

 

4. Log类包装

using System;

using System.Collections.Generic;

using System.Text;





using log4net;



[assembly: log4net.Config.XmlConfigurator(Watch = true)]

namespace BLL

{

    public class LogBLL

    {

        static ILog loger;

        public ILog LogerInstance

        {

            get

            {

                if (loger == null)

                    loger = LogManager.GetLogger("DBLogger");

                return loger;

            }



        }





        protected void LogException(Exception ex)

        {

            LogerInstance.Error("",ex);

        }



        protected void LogInfo(string msg)

        {

            LogerInstance.Info(msg);

        }



    }

}

5 建表脚本

CREATE TABLE [dbo].[Log] (

    [Id] [int] IDENTITY (1, 1) NOT NULL,

    [Date] [datetime] NOT NULL,

    [Thread] [varchar] (255) NOT NULL,

    [Level] [varchar] (50) NOT NULL,

    [Logger] [varchar] (255) NOT NULL,

    [Message] [varchar] (4000) NOT NULL,

    [Exception] [varchar] (2000) NULL

)


我是傻瓜老师,今天来讲一下如何如何使用log4net,当然是在。net.

首先保证你已经下了log4net.dll文件,并引入到程序的bin文件夹里,否则...... 

 

1:首先在web.config中的<configSections>...</configSections>中加入:

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

 

2:然后在<configuration>...</configuration>中加入:

<log4net debug="false">
  
   <appender name="LogFileAppender" type="log4net.Appender.FileAppender" >
    <param name="File" value="d:\Applog.txt" />
    <param name="datePattern" value="yyyy-MM-dd HH:mm" />
    <param name="AppendToFile" value="true" />
    <layout type="log4net.Layout.PatternLayout">
     <param name="ConversionPattern" value="“%d %t %p %l %m %n" />    
    </layout>   
   </appender>
  
   <appender name="HttpTraceAppender" type="log4net.Appender.ASPNetTraceAppender" >
    <layout type="log4net.Layout.PatternLayout">
     <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />    
    </layout>   
   </appender>
  
   <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
    <layout type="log4net.Layout.PatternLayout">
     <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />    
    </layout>   
   </appender>
  
   <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <param name="File" value="d:\Log.txt" />
    <param name="AppendToFile" value="true" />
    <param name="MaxSizeRollBackups" value="10" />
    <param name="MaximumFileSize" value="5MB" />
    <param name="RollingStyle" value="Size" />
    <param name="StaticLogFileName" value="true" />
    <layout type="log4net.Layout.PatternLayout">
     <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %m%n" />    
    </layout>   
   </appender>
  
   <root>
    <level value="DEBUG" />
    <appender-ref ref="LogFileAppender" />   
   </root>
  
 </log4net>

 

3:最后在需要记录日志的aspx.cscs类里,先定义一个log日志对象:

private static log4net.ILog log = log4net.LogManager.GetLogger("debug");

 4:在Global.asax文件的

voidApplication_Start(objectsender,EventArgse) 

    {

        // Code that runs on application startup

        //注册日志配置

        log4net.Config.XmlConfigurator.Configure(); 

    }

    

5:调用:

在需要记录日志的代码块处,加一行这个,ok!

log.Debug("XX的操作被记录了");

 

6:最最后,对web.config中的“%d %t %p %l %m %n”一一讲解:

%d:输出日志时间点的日期或时间,可以在其后指定格式,比如:%d{yyyy-mm-dd hh:mm:ss},输出类似:2005-7-19 17:49:27,刚好适合插入sqlserver;

%t:产生该日志事件的线程名;

%p:日志的log_level,如debug、warn或者info;

%c:输出所属的类目,通常就是所在类的全名,如“inotes.default”;

%m:日志的内容;

%l:输出日志事件的发生位置,包括类目名、发生的线程,以及在代码中的行数。

%n  输出一个回车换行符,windows平台为“\r\n”,unix平台为“\n” 

 

如果你还是不大了解,那就用%d %t %p %l %m %n 这个格式吧,反正我是如此设置的,清晰明了。

你可能感兴趣的:(log)