你的位置:首页 > ASP.net教程

[ASP.net教程]在VS2013中使用Log4net


大致分为3个步骤

  1. 引用Log4net

  2. 配置Log4net
    配置目标:
    1. 启用内部调试
    2. 按照日期分割日志文件 1小时1个
    3. 按照日志容量分割文件 10KB 1个
    4. 按照日志大小, 时间分割文件
    5. 输出到SQL SERVER(需要先建立表)

    建立表代码如下:
    CREATE TABLE [dbo].[Log](  [Id] [int] IDENTITY(1,1) NOT NULL,  [AppDomain] [nvarchar](255) NULL,  [Logger] [nvarchar](255) NOT NULL,  [Level] [nvarchar](50) NOT NULL,  [Thread] [nvarchar](255) NOT NULL,  [File] [nvarchar](500) NULL,  [Line] [nvarchar](50) NULL,  [Identity] [nvarchar](50) NULL,  [UserName] [nvarchar](50) NULL,  [Date] [datetime] NOT NULL,  [RunTime] [int] NULL,  [Message] [nvarchar](4000) NULL,  [Exception] [text] NULL, CONSTRAINT [PK_Log] PRIMARY KEY CLUSTERED (  [Id] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]GOALTER TABLE [dbo].[Log] ADD CONSTRAINT [DF_Log_Date] DEFAULT (getdate()) FOR [Date]GO

     

    配置如下:
    <??><configuration> <configSections>  <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" /> </configSections> <appSettings>  <!-- 开启内部调试 比如, 配置好了日志记录到数据库(Mysql、Oracle、Sql Server)等, 但就是记录不上, 又找不到原因时, 可以查看这个log排查原因 -->  <add key="log4net.Internal.Debug" value="true"/> </appSettings> <system.diagnostics>  <trace autoflush="true">   <listeners>    <add name="textWriterTraceListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="Log/log4net.Internal.Debug.log" />   </listeners>  </trace> </system.diagnostics> <log4net>  <!-- 按照日期分割日志文件 1小时1个 -->  <appender name="LogFileAppenderByDate" type="log4net.Appender.RollingFileAppender">   <!-- 是否续写 -->   <param name="AppendToFile" value="true" />   <!--最小锁定模型以允许多个进程可以写入同一个文件 在使用RollingFileAppender的方式不支持多进程同時写一個日志文件; 使用FileAppender才可以 -->   <!--<param name="LockingModel" value="log4net.Appender.FileAppender+MinimalLock" />-->   <!--<param name="StaticLogFileName" value="true" />-->   <!-- 保存路径 -->   <param name="File" value="Log/" />   <param name="DatePattern" value="yyyy-MM-dd HH.LOG" />   <!-- 注意后缀必须要大写, 不然会生成位置类型的文件 -->   <param name="StaticLogFileName" value="false" />   <param name="RollingStyle" value="Date" />   <layout type="log4net.Layout.PatternLayout">    <param name="Header" value="&#xD;&#xA;---- Start --------------------------------------------&#xD;&#xA;" />    <param name="Footer" value="&#xD;&#xA;---- End --------------------------------------------&#xD;&#xA;" />    <param name="ConversionPattern" value="%newlineAppDomain: %appdomain %newlineLogger: %logger %newlineLevel: %level %newlineThreadId: %thread %newlineFile: %file %newlineLine: %line %newlineIdentity: %identity %newlineUserName: %username %newlineDateTime: %date{yyyy-MM-dd HH:mm:ss.fff} %newlineRunTime: %timestamp(ms) %newlineMessage: %message %newlineException: %exception %newline%newline" />   </layout>  </appender>  <!-- 按照日志容量分割文件 10KB 1个 -->  <appender name="LogFileAppenderBySize" type="log4net.Appender.RollingFileAppender">   <!--是否续写-->   <param name="AppendToFile" value="true" />   <!--最小锁定模型以允许多个进程可以写入同一个文件 在使用RollingFileAppender的方式不支持多进程同時写一個日志文件; 使用FileAppender才可以 -->   <!--<param name="LockingModel" value="log4net.Appender.FileAppender.MinimalLock" />-->   <!--按照文件的大小进行变换日志文件-->   <param name="RollingStyle" value="Size" />   <!--生成 log.txt, log.txt.1, log.txt.2-->   <param name="File" value="Log/log.txt" />   <!--单个文件最大数量 好像只有在 按Size分割时有效-->   <param name="MaximumFileSize" value="15KB"/>   <!--保留的log文件数量 超过此数量后 自动删除之前的  好像只有在 按Size分割时有效-->   <param name="MaxSizeRollBackups" value="3" />   <param name="StaticLogFileName" value="false" />   <layout type="log4net.Layout.PatternLayout">    <param name="Header" value="&#xD;&#xA;---- Start --------------------------------------------&#xD;&#xA;" />    <param name="Footer" value="&#xD;&#xA;---- End --------------------------------------------&#xD;&#xA;" />    <param name="ConversionPattern" value="%newlineAppDomain: %appdomain %newlineLogger: %logger %newlineLevel: %level %newlineThreadId: %thread %newlineFile: %file %newlineLine: %line %newlineIdentity: %identity %newlineUserName: %username %newlineDateTime: %date{yyyy-MM-dd HH:mm:ss.fff} %newlineRunTime: %timestamp(ms) %newlineMessage: %message %newlineException: %exception %newline%newline" />   </layout>  </appender>  <!--输出到文件-->  <appender name="LogFileAppenderBySizeAndDate" type="log4net.Appender.RollingFileAppender">   <param name="File" value="Log/" />   <param name="AppendToFile" value="true" />   <!-- 切割最多文件数 -1表示不限制产生日志文件数-->   <param name="MaxSizeRollBackups" value="-1"/>   <!-- 每个文件的大小限制 -->   <param name="MaximumFileSize" value="10KB"/>   <!-- RollingStyle Composite 综合 Size 按大小 Date 按时间 -->   <param name="RollingStyle" value="Composite" />   <!--如果要在这个文件名后面加上.log后缀,必须使用转义字符-->   <!--<param name="DatePattern" value="&quot;Logs_&quot;yyyyMMdd&quot;.txt&quot;" />-->   <param name="DatePattern" value="yyyyMMdd-HH.mm&quot;.log&quot;" />   <param name="StaticLogFileName" value="false" />   <layout type="log4net.Layout.PatternLayout">    <param name="Header" value="&#xD;&#xA;---- Start --------------------------------------------&#xD;&#xA;" />    <param name="Footer" value="&#xD;&#xA;---- End --------------------------------------------&#xD;&#xA;" />    <param name="ConversionPattern" value="%newlineAppDomain: %appdomain %newlineLogger: %logger %newlineLevel: %level %newlineThreadId: %thread %newlineFile: %file %newlineLine: %line %newlineIdentity: %identity %newlineUserName: %username %newlineDateTime: %date{yyyy-MM-dd HH:mm:ss.fff} %newlineRunTime: %timestamp(ms) %newlineMessage: %message %newlineException: %exception %newline%newline" />   </layout>   <filter type="log4net.Filter.LevelRangeFilter">    <param name="LevelMin" value="ALL" />    <param name="LevelMax" value="OFF" />   </filter>  </appender>  <!--输出到SQL Server-->  <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">   <bufferSize value="100" />   <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />   <connectionString value="Data Source=.;Initial Catalog=log4netTest;User ID=sa;Password=sa" />   <commandText value="INSERT INTO [dbo].[Log]                   ([AppDomain]                   ,[Logger]                   ,[Level]                   ,[Thread]                   ,[File]                   ,[Line]                   ,[Identity]                   ,[UserName]                   ,[Date]                   ,[RunTime]                   ,[Message]                   ,[Exception])                VALUES                   (@appDomain                   ,@logger                   ,@log_level                   ,@thread                   ,@file                   ,@line                   ,@identity                   ,@userName                   ,@log_date                   ,@runtime                   ,@message                   ,@exception)" />   <parameter>    <parameterName value="@appDomain" />    <dbType value="String" />    <size value="255" />    <layout type="log4net.Layout.PatternLayout">     <conversionPattern value="%appdomain" />    </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="@log_level" />    <dbType value="String" />    <size value="50" />    <layout type="log4net.Layout.PatternLayout">     <conversionPattern value="%level" />    </layout>   </parameter>   <parameter>    <parameterName value="@thread" />    <dbType value="String" />    <size value="255" />    <layout type="log4net.Layout.PatternLayout">     <conversionPattern value="%thread" />    </layout>   </parameter>   <parameter>    <parameterName value="@file" />    <dbType value="String" />    <size value="500" />    <layout type="log4net.Layout.PatternLayout">     <conversionPattern value="%file" />    </layout>   </parameter>   <parameter>    <parameterName value="@line" />    <dbType value="String" />    <size value="50" />    <layout type="log4net.Layout.PatternLayout">     <conversionPattern value="%line" />    </layout>   </parameter>   <parameter>    <parameterName value="@identity" />    <dbType value="String" />    <size value="50" />    <layout type="log4net.Layout.PatternLayout">     <conversionPattern value="%identity" />    </layout>   </parameter>   <parameter>    <parameterName value="@userName" />    <dbType value="String" />    <size value="50" />    <layout type="log4net.Layout.PatternLayout">     <conversionPattern value="%username" />    </layout>   </parameter>   <parameter>    <parameterName value="@log_date" />    <dbType value="DateTime" />    <layout type="log4net.Layout.RawTimeStampLayout" />   </parameter>   <parameter>    <parameterName value="@runtime" />    <dbType value="Int32" />    <layout type="log4net.Layout.PatternLayout">     <conversionPattern value="%timestamp" />    </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="8000" />    <layout type="log4net.Layout.ExceptionLayout" />   </parameter>  </appender>  <root>   <!-- 配置日志的级别,低于此级别的就不写到日志里面去 OFF、FATAL、ERROR, WARN, INFO, DEBUG, ALL -->   <level value="DEBUG" />   <appender-ref ref="LogFileAppenderByDate" />   <appender-ref ref="LogFileAppenderBySize" />   <appender-ref ref="LogFileAppenderBySizeAndDate" />   <appender-ref ref="AdoNetAppender" />  </root> </log4net>    <startup>     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />  </startup></configuration>

  3. 调用Log4Net

    首先在AssemblyInfo.cs类添加一行代码
    [assembly: log4net.Config.true)]

     

    编写调用方法
    class Program{    private static readonly ILog log = LogManager.GetLogger(typeof(Program).Name);    static void Main(string[] args)    {      for (int i = 0; i < 50; i++)      {        try        {          int a = 8, b = 0, c = 0;          c = a / b;        }        catch (Exception ex)        {          if (log.IsErrorEnabled)          {            log.Error(null, ex);          }          if (log.IsDebugEnabled)          {            log.Debug("Debug", ex);          }        }      }      Console.ReadKey();    }}

     

查看运行结果:

  • 路径下生成的文件