如果在项目当中需要使用log4net来记录日志,大致分为以下三步
1,创建log4net配置文件
2,读取配置文件节点
3,记录日志信息
第一步:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
</configSections>
<log4net>
<logger name="logerror">
<level value="ERROR"/>
<appender-ref ref="ErrorAppender"/>
</logger>
<logger name="loginfo">
<level value="INFO"/>
<appender-ref ref="InfoAppender"/>
</logger>
<appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="..//..//Log//Error//"/>
<param name="AppendToFile" value="true"/>
<param name="MaxSizeRollBackups" value="100"/>
<param name="MaxFileSize" value="1024"/>
<param name="StaticLogFileName" value="false"/>
<param name="DatePatten" value="yyyy-MM-dd".txt""/>
<param name="RollingStyle" value="Date"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="异常时间:date %n 异常位置:[ %thread]
( %file: %line) %消息描述: %message % 异常: %exception %n %n
"/>
</layout>
</appender>
<appender name="InfoAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="..//..//Log//Info//"/>
<param name="AppendToFile" value="true"/>
<param name="MaxSizeRollBackups" value="100"/>
<param name="MaxFileSize" value="1024"/>
<param name="StaticLogFileName" value="false"/>
<param name="DatePatten" value="yyyy-MM-dd".txt""/>
<param name="RollingStyle" value="Date"/>
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value=" %n异常时间: %date 消息描述: %m"/>
</layout>
</appender>
</log4net>
</configuration>
第二步:
public class LogHelper
{
private readonly log4net.ILog logInfo;
private readonly log4net.ILog logError;
public LogHelper
{
log4net.Config.XmlConfigure (new System.IO.FileInfo("配置文件的位置"));
///读取配置文件节点,实例化记录信息对象和错误对象
logInfo = log4net.LogManager.GetLogger("loginfo");
logError = log4net.LogManager.GetLogger("logerror");
}
public static void WriteInfo(string message)
{
try
{
if(loginfo.IsInfoEnabled)
{
loginfo.Info(message);
}
}
catch{}
}
public static void WriteError(string error,Exception ex)
{
try
{
if(logError.IsErrorEnabled)
{
loginfo.Info(error,ex);
}
}
catch
{
}
}
}
第三步
LogHelper logHelper = new LogHelper();
logHelper.WriteInfo(“输出记录信息”);
也可以把第二步和第三步合并一起来写
log4net.LogManager.GetLogger(“loginfo”).Info(“输出记录信息”);