日志记录有助于我们快速的进行错误排查,以下是简单的日志记录步骤,下面以一个简单的MVC程序为例来介绍
1.先创建一个简单的mvc程序
2.在项目中引入log4net.dll
3.添加TestLogNet4类
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Configuration;
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Logger/log4net.config", ConfigFileExtension = "config", Watch = true)]
namespace WebApplication1
{
public class TestLogNet4
{
//信息日志存储文件夹
private static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo");
//错误日志存储文件夹
private static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror");
/// <summary>
/// 记录日志
/// </summary>
/// <param name="message">日志消息</param>
public static void WriteLog(string message)
{
if (loginfo.IsInfoEnabled )
{
if (message != null && message.Length > 0)
{
loginfo.Info(message);
}
}
}
}
}
4.添加Logger、子文件夹(LogError 、LogInfo)和配置文件log4net.config
5.log4net.config配置如下:
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<!-- 错误日志类-->
<logger name="logerror">
<level value="ALL" />
<appender-ref ref="ErrorAppender" />
</logger>
<!-- 信息日志类 -->
<logger name="loginfo">
<level value="ALL" />
<appender-ref ref="InfoAppender" />
</logger>
<!-- 错误日志附加介质-->
<appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Logger\\LogError\\" />
<param name="AppendToFile" value="true" />
<param name="MaxSizeRollBackups" value="100" />
<param name="MaxFileSize" value="10240" />
<param name="StaticLogFileName" value="false" />
<param name="DatePattern" value="yyyyMMdd".txt"" />
<param name="RollingStyle" value="Date" />
<!--布局-->
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="<HR COLOR=red>%n【异常时间】:%d [%t] <BR>%n【异常级别】:%-5p <BR>%n【异 常 类】:%c [%x] <BR>%n%m <BR>%n <HR Size=1>" />
</layout>
</appender>
<!-- 信息日志附加介质-->
<appender name="InfoAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="Logger\\LogInfo\\" />
<param name="AppendToFile" value="true" />
<param name="MaxFileSize" value="1" />
<param name="MaxSizeRollBackups" value="100" />
<param name="StaticLogFileName" value="false" />
<param name="DatePattern" value="yyyyMMdd".txt"" />
<param name="RollingStyle" value="Date" />
<!-- 信息日志布局-->
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="<HR COLOR=blue>%n日志时间:%d [%t] <BR>%n日志级别:%-5p <BR>%n日 志 类:%c [%x] <BR>%n%m <BR>%n <HR Size=1>" />
</layout>
</appender>
</log4net>
6.WebTest.ASPX调用如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TestLogNet4.WriteLog("测试测试测试");
}
}
}
7.运行程序中的WebTest.ashx页面之后,查看项目下Logger文件夹下的LogInfo中是否生成日志文件,同一天的日志文件在同一个文本文件中。