【注意:logInfo.IsInfoEnabled 总是false问题。】
1:放在log4net.config 所在的项目下的AssemblyInfo.cs 末尾。(不清楚就每个 项目都加这句吧);另外注意文件名要一致;
2:lo4net.config 属性:“始终复制”
【一】AssemblyInfo.cs 中添加:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", ConfigFileExtension = "config", Watch = true)]
【二】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="ErrorLog">
<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="C:\Proj\MyLog\Error\" />
<param name="AppendToFile" value="true" />
<param name="MaxFileSize" value="10240" />
<param name="MaxSizeRollBackups" value="30" />
<param name="StaticLogFileName" value="false" />
<param name="DatePattern" value="yyyyMMddHH.TXT" />
<param name="RollingStyle" value="Date" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%newline%date [%thread] %-5level %logger - %message%newline" />
<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="C:\Proj\MyLog\Info\" />
<param name="AppendToFile" value="true" />
<param name="MaxFileSize" value="10240" />
<param name="MaxSizeRollBackups" value="30" />
<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="%n日志时间:%d [%t] %n日 志 类:%c [%x] %n%m %n" />
<param name="Header" value="-----------BEGIN-----------" />
<param name="Footer" value="------------END------------" />
</layout>
</appender>
</log4net>
</configuration>
【三】logHelper.cs
using System;
namespace XXXX
{
public class LogHelper
{
private static readonly log4net.ILog logInfo = log4net.LogManager.GetLogger("InfoLog");
/// <summary>
/// 普通日志
/// </summary>
/// <param name="message">日志内容</param>
public static void Info(string message)
{
if (logInfo.IsInfoEnabled)
{
logInfo.Info(message);
}
}
private static readonly log4net.ILog logError = log4net.LogManager.GetLogger("ErrorLog");
/// <summary>
/// 错误日志
/// </summary>
/// <param name="message">错误日志</param>
public static void Error(string message)
{
if (logError.IsErrorEnabled)
{
logError.Error(message);
}
}
/// <summary>
/// 错误日志
/// </summary>
/// <param name="message">错误日志</param>
public static void Error(Exception ex)
{
if (logError.IsErrorEnabled)
{
logError.Error(ex);
}
}
}
}