1. log4net简介
log4net是.Net下一个非常优秀的开源日志记录组件。log4net记录日志的功能非常强大。它可以将日志分不同的等级,以不同的格式,输出到不同的媒介。Java平台下,它还有一个姐妹组件——log4j。
log4net的下载地址:http://logging.apache.org/log4net/download.html
2. log4net的组成
log4net主要由五部分组成,分别为Appenders、Filters、Layouts、Loggers和Object Renders。
3. 在程序中使用log4net
在使用log4net前要先做一些配置的工作。配置工作可以在配置文件中完成也可以再程序中用代码完成。我们主要讲在配置文件中如何配置log4net,因为这样更方便灵活,而且还不用重新编译代码。
废话少说,看一个完整的log4net配置实例:
(1)、Web.config中:
<configuration>
<configSections>
<!--注册lognet-->
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
</configSections>
<!--站点日志配置部分-->
<log4net>
<root>
<priority value="ALL"/>
<appender-ref ref="TraceAppender"/>
<appender-ref ref="ConsoleAppender"/>
<appender-ref ref="RollingFileAppender"/>
</root>
<appender name="TraceAppender" type="log4net.Appender.TraceAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline"/>
</layout>
</appender>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline"/>
</layout>
</appender>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="Log\SysLog"/><!--日志文件夹及文件名开头-->
<appendToFile value="true"/><!--是否追加到文件-->
<RollingStyle value="Date"/><!--日期的格式-->
<DatePattern value="yyyy-MM-dd".log""/><!--文件名后面加上.log后缀,必须使用转义字符-->
<maximumFileSize value="1MB" /><!--最大文件大小-->
<StaticLogFileName value="false"/><!--日志文件名是否为静态-->
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%newline%date [%thread] %-5level %logger [%property{NDC}] - %message%newline%newline"/>
<param name="Header" value=" --------------------------网站运行过程中产生的错误-------------------------- "/>
<param name="Footer" value=" -------------------------------------测试:GZQ------------------------------------- "/>
</layout>
</appender>
</log4net>
<!--End站点日志配置部分-->
如果记录日志到数据库:
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<log4net>
<logger name="LogSystem">
<level value="ALL"/>
<appender-ref ref="AdoNetAppender_SqlServer" />
</logger>
<!--记录到sqlserver数据库方式-->
<appender name="AdoNetAppender_SqlServer" type="log4net.Appender.AdoNetAppender">
<buffersize value="1" />
<connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<connectionString value="data source=xxx;initial catalog=xxx;integrated security=false;persist security info=True;User ID=xxx;Password=xxx"/>
<commandText value="INSERT INTO SysLog ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)"/>
<parameter>
<parameterName value="@log_date"/>
<dbType value="DateTime"/>
<layout type="log4net.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}"/>
</parameter>
<parameter>
<parameterName value="@thread"/>
<dbType value="String"/>
<size value="255"/>
<layout type="log4net.Layout.PatternLayout" value="%thread"/>
</parameter>
<parameter>
<parameterName value="@log_level"/>
<dbType value="String"/>
<size value="50"/>
<layout type="log4net.Layout.PatternLayout" value="%level"/>
</parameter>
<parameter>
<parameterName value="@logger"/>
<dbType value="String"/>
<size value="255"/>
<layout type="log4net.Layout.PatternLayout" value="%logger"/>
</parameter>
<parameter>
<parameterName value="@message"/>
<dbType value="String"/>
<size value="4000"/>
<layout type="log4net.Layout.PatternLayout" value="%message"/>
</parameter>
</appender>
</log4net>
</configuration>
(2)、Global.asax文件中:
<%@ Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
//在应用程序启动时运行的代码
//初始化日志使用封装类
AppLog.Init();
AppLog.Write("Web站点运行...", AppLog.LogMessageType.Info);
}
void Application_End(object sender, EventArgs e)
{
//在应用程序关闭时运行的代码
AppLog.Write("Web站点关闭...", AppLog.LogMessageType.Info);
}
void Application_Error(object sender, EventArgs e)
{
//在出现未处理的错误时运行的代码
Exception ex = Server.GetLastError();
if (ex != null)
{
//写入错误日志
AppLog.Write("[Exception]:", AppLog.LogMessageType.Error, ex);
//如果是 HttpException 异常 不处理, 显示403 404 页面
if (ex is HttpException)
{
HttpException httpEx = ex as HttpException;
if (httpEx.GetHttpCode() == 403 || httpEx.GetHttpCode() == 404)
return;
}
//Response.Redirect("~/Error.aspx");
}
}
void Session_Start(object sender, EventArgs e)
{
//在新会话启动时运行的代码
}
void Session_End(object sender, EventArgs e)
{
//在会话结束时运行的代码。
// 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
// InProc 时,才会引发 Session_End 事件。如果会话模式
//设置为 StateServer 或 SQLServer,则不会引发该事件。
}
</script>
(3)、在App_Code文件夹下添加文件AppLog.cs:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using log4net;
using log4net.Config;
/// <summary>
///AppLog 的摘要说明
/// </summary>
public class AppLog
{
/// <summary>
/// 日志处理
/// </summary
private AppLog() { }
private const string LOG_REPOSITORY = "Default"; // this should likely be set in the web config.
private static ILog m_log;
/// <summary>
/// 初始化日志系统
/// 在系统运行开始初始化
/// Global.asax Application_Start内
/// </summary>
public static void Init()
{
log4net.Config.XmlConfigurator.Configure();
}
/// <summary>
/// 写入日志
/// </summary>
/// <param name="message">日志信息</param>
/// <param name="messageType">日志类型</param>
public static void Write(string message, LogMessageType messageType)
{
DoLog(message, messageType, null, Type.GetType("System.Object"));
}
/// <summary>
/// 写入日志
/// </summary>
/// <param name="message">日志信息</param>
/// <param name="messageType">日志类型</param>
/// <param name="type"></param>
public static void Write(string message, LogMessageType messageType, Type type)
{
DoLog(message, messageType, null, type);
}
/// <summary>
/// 写入日志
/// </summary>
/// <param name="message">日志信息</param>
/// <param name="messageType">日志类型</param>
/// <param name="ex">异常</param>
public static void Write(string message, LogMessageType messageType, Exception ex)
{
DoLog(message, messageType, ex, Type.GetType("System.Object"));
}
/// <summary>
/// 写入日志
/// </summary>
/// <param name="message">日志信息</param>
/// <param name="messageType">日志类型</param>
/// <param name="ex">异常</param>
/// <param name="type"></param>
public static void Write(string message, LogMessageType messageType, Exception ex,
Type type)
{
DoLog(message, messageType, ex, type);
}
/// <summary>
/// 断言
/// </summary>
/// <param name="condition">条件</param>
/// <param name="message">日志信息</param>
public static void Assert(bool condition, string message)
{
Assert(condition, message, Type.GetType("System.Object"));
}
/// <summary>
/// 断言
/// </summary>
/// <param name="condition">条件</param>
/// <param name="message">日志信息</param>
/// <param name="type">日志类型</param>
public static void Assert(bool condition, string message, Type type)
{
if (condition == false)
Write(message, LogMessageType.Info);
}
/// <summary>
/// 保存日志
/// </summary>
/// <param name="message">日志信息</param>
/// <param name="messageType">日志类型</param>
/// <param name="ex">异常</param>
/// <param name="type">日志类型</param>
private static void DoLog(string message, LogMessageType messageType, Exception ex,
Type type)
{
m_log = LogManager.GetLogger(type);
switch (messageType)
{
case LogMessageType.Debug:
AppLog.m_log.Debug(message, ex);
break;
case LogMessageType.Info:
AppLog.m_log.Info(message, ex);
break;
case LogMessageType.Warn:
AppLog.m_log.Warn(message, ex);
break;
case LogMessageType.Error:
AppLog.m_log.Error(message, ex);
break;
case LogMessageType.Fatal:
AppLog.m_log.Fatal(message, ex);
break;
}
}
/// <summary>
/// 日志类型
/// </summary>
public enum LogMessageType
{
/// <summary>
/// 调试
/// </summary>
Debug,
/// <summary>
/// 信息
/// </summary>
Info,
/// <summary>
/// 警告
/// </summary>
Warn,
/// <summary>
/// 错误
/// </summary>
Error,
/// <summary>
/// 致命错误
/// </summary>
Fatal
}
}
(4)、将log4net.dll拷贝到bin文件夹下
到此就OK了,系统运行后就可以在根目录的Log文件夹下看到你的网站运行生成的系统日志文件了,并且可以记录整个网站运行过程中产生的异常错误。