https://www.cnblogs.com/lzrabbit/archive/2012/03/23/2413180.html
https://blog.csdn.net/guyswj/article/details/81940188
一、引用log4net
二、在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 debug="true">
<appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender">
<!--日志路径-->
<param name="File" value="bin\\log\\logError\\" />
<!--是否向文件中追加日志-->
<param name="AppendToFile" value="true" />
<!--按照何种方式产生多个日志文件(日期[Date],文件大小[Size],混合[Composite])-->
<param name="RollingStyle" value="Composite" />
<!--日志文件名格式为:2008-08-31.log-->
<param name="DatePattern" value="yyyy-MM-dd".log"" />
<!--日志保留天数-->
<param name="MaxSizeRollBackups" value="20" />
<!--每个文件的大小。只在混合方式与文件大小方式下使用。超出大小后在所有文件名后自动增加正整数重新命名,数字最大的最早写入。可用的单位:KB|MB|GB。不要使用小数,否则会一直写入当前日志-->
<param name="MaximumFileSize" value="1024KB" />
<!--日志文件名是否是固定不变的-->
<param name="StaticLogFileName" value="false" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d %p %m "/>
</layout>
</appender>
<appender name="InfoAppender" type="log4net.Appender.RollingFileAppender">
<param name="File" value="bin\\log\\logInfo\\" />
<param name="AppendToFile" value="true" />
<param name="RollingStyle" value="Date" />
<param name="DatePattern" value="yyyy-MM-dd".log"" />
<param name="MaxSizeRollBackups" value="20" />
<param name="MaximumFileSize" value="1024KB" />
<param name="StaticLogFileName" value="false" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d %m %n" />
</layout>
</appender>
<logger name="logerror">
<level value="ALL" />
<appender-ref ref="ErrorAppender" />
</logger>
<logger name="loginfo">
<level value="ALL" />
<appender-ref ref="InfoAppender" />
</logger>
</log4net>
</configuration>
四、封装LogHelper类
public class LogHelper
{
public readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo");
public readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror");
public void Info(string msg)
{
if (loginfo.IsInfoEnabled)
{
loginfo.Info(msg);
}
}
public void Error(string msg, Exception e)
{
if (logerror.IsErrorEnabled)
{
logerror.Error(msg, e);
}
}
//public void Debug(string msg, Exception e)
//{
// //if (logdebug.IsErrorEnabled)
// //{
// logerror.Debug(msg, e);
// //}
//}
}
五、调用示例
LogHelper logHelper = new LogHelper();
logHelper.Info(string.Format("当前的时间{0}", DateTime.Now.ToString()));
logHelper.Error("errorakkpkey", new Exception("log4net测试致命信息"));