使用log4net可以很方便地为应用添加日志功能。应用Log4net,开发者可以很精确地控制日志信息的输出,减少了多余信息,提高了日志记录性能。同时,通过外部配置文件,用户可以不用重新编译程序就能改变应用的日志行为,使得用户可以根据情况灵活地选择要记录的信息。
那么我们如何在Web项目中使用Log4Net呢?
一、基本配置
1、下载Log4Net,地址如下:http://logging.apache.org/log4net/download_log4net.cgi,如下图所示:
2、下载到本地后,进行解压,,并找到对应版本的.NET Framework版本,如下图所示:
3、在项目中添加Log4Net.DLL的引用,如下图所示:
4、在Web项目根目录下创建log4net.config配置文件,如下图所示:
配置文件log4new.config XML代码如下:
<?xml version="1.0" encoding="utf-8" ?> <log4net debug="false"> <appender name="LogFileAppender" type="log4net.Appender.FileAppender"> <param name="File" value="Log/AT.log"/> <param name="datePattern" value="YY-MM-dd HH:mm"/> <param name="AppendToFile" value="true"/> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %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"> <file value="log\AT"/> <appendToFile value="true"/> <rollingStyle value="Date"/> <datePattern value="_yyyyMMdd'.log'"/> <staticLogFileName value="false"/> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%d [%t] %-5p %c - %m%n"/> </layout> </appender> <root> <level value="INFO"/> <!--<level value="ERROR" />--> <appender-ref ref="RollingLogFileAppender"/> </root> </log4net>
5、项目中添加一个LogHelper.cs操作类,这样可以之后的其他页面进行调用,如下图所示:
LogHelper.cs类代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Web; [assembly: log4net.Config.XmlConfigurator(Watch = true)] namespace APESM_GGJ.CommonClass { public class LogHelper { /// <summary> /// 输出日志到Log4Net /// </summary> /// <param name="t"></param> /// <param name="ex"></param> #region static void WriteLog(Type t, Exception ex) public static void WriteLog(Type t, Exception ex) { log4net.ILog log = log4net.LogManager.GetLogger(t); log.Error("Error", ex); } #endregion /// <summary> /// 输出日志到Log4Net /// </summary> /// <param name="t"></param> /// <param name="msg"></param> #region static void WriteLog(Type t, string msg) public static void WriteLog(Type t, string msg) { log4net.ILog log = log4net.LogManager.GetLogger(t); log.Error(msg); } #endregion } }
方法中添加如下代码:
protected void Application_Start(object sender, EventArgs e) { //应用程序启动时,自动加载配置log4Net XmlConfigurator.Configure(); }
配置文件代码如下:
<?xml version="1.0" encoding="utf-8"?> <!-- 有关如何配置 ASP.NET 应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <log4net configSource="log4net.config"/> <system.web> <httpModules> <!--重写IHttpModule类,需要配置的信息--> <!--<add name="FilterModule" type="APESM_GGJ.FilterModule,APESM_GGJ" />--> </httpModules> <compilation debug="true" targetFramework="4.0" /> </system.web> </configuration>
8、在页面中调用,进行日志写入,如下图所示:
页面调用代码:
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { LogHelper.WriteLog(typeof(Login), "测试在Web项目中使用Log4Net日志!"); } }
9、查看项目根目录下的Log文件夹,可以看见我们写入的日志log文件,如下图所示:
至此在Web项目中使用Log4Net进行日志记录的功能就已经实现了。
---------------------------------------------------------------------------------------------------------------------
二、扩展
上面实现的是将日志写入到文件中,那么如果想写入到数据库中,该如何操作,这里以SQL Server为例,创建一个日志表,然后修改log4net.config文件,如下代码:
<?xml version="1.0" encoding="utf-8" ?> <log4net debug="false"> <appender name="ADONetAppender" type="log4net.Appender.ADONetAppender"> <bufferSize value="10" /> <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <connectionString value="DATABASE=CSDN;SERVER=.;UID=sa;PWD=111111;Connect Timeout=15;" /> <commandText value="INSERT INTO ErrorLog ([dtDate],[sThread],[sLevel],[sLogger],[sMessage],[sException]) 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="100" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%t" /> </layout> </parameter> <parameter> <parameterName value="@log_level" /> <dbType value="String" /> <size value="200" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%p" /> </layout> </parameter> <parameter> <parameterName value="@logger" /> <dbType value="String" /> <size value="500" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%logger" /> </layout> </parameter> <parameter> <parameterName value="@message" /> <dbType value="String" /> <size value="3000" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%m" /> </layout> </parameter> <parameter> <parameterName value="@exception" /> <dbType value="String" /> <size value="4000" /> <layout type="log4net.Layout.ExceptionLayout" /> </parameter> </appender> <!-- setup the root category, add the appenders and set the default level --> <root> <level value="WARN"/> <level value="INFO"/> <level value="DEBUG"/> <level value="FINE"/> <appender-ref ref="ADONetAppender" /> </root> <!-- specify the level for some specific categories --> <logger name="iNotes"> <level value="WARN"/> <level value="INFO"/> <level value="DEBUG"/> <level value="FINE"/> <appender-ref ref="ADONetAppender"/> </logger> <logger name="StellaLogger"> <level value="ALL"/> <appender-ref ref="AdoNetAppender" /> </logger> </log4net>
测试时将其修改为1
生产环境建议100
上面配置节中数据库名,用户名和密码,根据实际情况进行修改。
数据库表ErrorLog创建语句为:
CREATE TABLE ErrorLog( nId bigint IDENTITY(1,1) NOT NULL, dtDate datetime NOT NULL, sThread nvarchar(100) NOT NULL, sLevel nvarchar(200) NOT NULL, sLogger nvarchar(500) NOT NULL, sMessage nvarchar(3000) NOT NULL, sException nvarchar(4000) NULL );
如下图所示:
三、整合
想同时保存到日志文件和数据库,log4net.config的文件配置如下XML代码所示:
<?xml version="1.0" encoding="utf-8" ?> <log4net debug="false"> <!-- 将日志信息写入SQL Server数据库 2015-09-29--> <appender name="ADONetAppender" type="log4net.Appender.ADONetAppender"> <bufferSize value="1" /> <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <connectionString value="DATABASE=CSDN;SERVER=.;UID=sa;PWD=111111;Connect Timeout=15;" /> <commandText value="INSERT INTO ErrorLog ([dtDate],[sThread],[sLevel],[sLogger],[sMessage],[sException]) 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="100" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%t" /> </layout> </parameter> <parameter> <parameterName value="@log_level" /> <dbType value="String" /> <size value="200" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%p" /> </layout> </parameter> <parameter> <parameterName value="@logger" /> <dbType value="String" /> <size value="500" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%logger" /> </layout> </parameter> <parameter> <parameterName value="@message" /> <dbType value="String" /> <size value="3000" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%m" /> </layout> </parameter> <parameter> <parameterName value="@exception" /> <dbType value="String" /> <size value="4000" /> <layout type="log4net.Layout.ExceptionLayout" /> </parameter> </appender> <!-- 将日志信息写入到项目日志文件 2015-09-29 --> <appender name="LogFileAppender" type="log4net.Appender.FileAppender"> <param name="File" value="Log/AT.log"/> <param name="datePattern" value="YY-MM-dd HH:mm"/> <param name="AppendToFile" value="true"/> <layout type="log4net.Layout.PatternLayout"> <param name="ConversionPattern" value="%d [%t] %-5p %c [%x] - %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"> <file value="log\AT"/> <appendToFile value="true"/> <rollingStyle value="Date"/> <datePattern value="_yyyyMMdd'.log'"/> <staticLogFileName value="false"/> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%d [%t] %-5p %c - %m%n"/> </layout> </appender> <!--设置根目录,添加appenders并设置默认日志等级 --> <root> <level value="WARN"/> <level value="INFO"/> <level value="DEBUG"/> <level value="FINE"/> <appender-ref ref="ADONetAppender" /> <appender-ref ref="RollingLogFileAppender"/> </root> <!-- 为特定的目录指定等级 --> <logger name="iNotes"> <level value="WARN"/> <level value="INFO"/> <level value="DEBUG"/> <level value="FINE"/> <appender-ref ref="ADONetAppender"/> <appender-ref ref="RollingLogFileAppender"/> </logger> <logger name="StellaLogger"> <level value="ALL"/> <appender-ref ref="AdoNetAppender" /> <appender-ref ref="RollingLogFileAppender"/> </logger> </log4net>
===========================================================================
如果觉得对您有帮助,微信扫一扫支持一下: