1、 下载Log4net组件:
http://logging.apache.org/log4net/download.html
http://archive.apache.org/dist/incubator/log4net/1.2.10/incubating-log4net-1.2.10.zip
2、解压出Log4net组件dll:
incubating-log4net-1.2.10.zip\log4net-1.2.10\bin\net\2.0\release:
log4net.xml
log4net.dll
3、引用log4net
4、添加log4net.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<log4net>
<root>
</root>
<logger name="Error">
<level value="ALL" />
<appender-ref ref="ErrorAppender" />
</logger>
<logger name="InfoLog">
<level value="ALL" />
<appender-ref ref="InfoAppender" />
</logger>
<appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender,log4net" >
<param name="File" type="" value="Log/Error" />
<param name="AppendToFile" value="true" />
<param name="RollingStyle" value="Date" />
<param name="DatePattern" value="yyyyMMdd" />
<param name="StaticLogFileName" value="false" />
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%n[%d] %c %n%m%n%n" />
<param name="Header" value="-----------BEGIN-----------" />
<param name="Footer" value="------------END------------" />
</layout>
</appender>
<appender name="InfoAppender" type="log4net.Appender.RollingFileAppender,log4net" >
<param name="File" type="" value="Log/Info" />
<param name="AppendToFile" value="true" />
<param name="RollingStyle" value="Date" />
<param name="DatePattern" value="yyyyMMdd" />
<param name="StaticLogFileName" value="false" />
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%n[%d] %c %n%m%n%n" />
<param name="Header" value="-----------BEGIN-----------" />
<param name="Footer" value="------------END------------" />
</layout>
</appender>
</log4net>
</configuration>
5、修改AssemblyInfo.cs
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
6、新增一个LogHelper类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ToolUtils
{
public class LogHelper
{
public static readonly log4net.ILog logInfo = log4net.LogManager.GetLogger("InfoLog");
public static readonly log4net.ILog logError = log4net.LogManager.GetLogger("Error");
/// <summary>
/// 普通日志
/// </summary>
/// <param name="message">日志内容</param>
public static void Info(string message)
{
if (logInfo.IsInfoEnabled)
{
logInfo.Info(message);
}
}
/// <summary>
/// 错误日志
/// </summary>
/// <param name="message">错误日志</param>
public static void Error(string message)
{
if (logError.IsErrorEnabled)
{
logError.Error(message);
}
}
}
}
7、在Program.cs文件中初始化log4net
log4net.Config.XmlConfigurator.Configure();
8、使用
LogHelper.Info("这是一条普通日志");
LogHelper.Error("这是一条错误日志");