WinForm log4net使用 (另一种)
1.安装程序包log4net.dll
2.AssemblyInfo.cs文件添加
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
3.App.config添加
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<!--Log4Net-->
<!-- Level的级别,由高到低 -->
<!-- None > Fatal > ERROR > WARN > DEBUG > INFO > ALL-->
<!-- 解释:如果level是ERROR,则在cs文件里面调用log4net的info()方法,则不会写入到日志文件中-->
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value=".\log\log_%date{yyyMMdd}.log" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<!--<datePattern value="yyyyMMddhhmmss'.log'"/>-->
<maxSizeRollBackups value="10" />
<maximumFileSize value="5MB" />
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
<param name="Header" value=" ----------------------header--------------------------
" />
<param name="Footer" value=" ----------------------footer--------------------------
" />
</layout>
</appender>
<root>
<level value="All" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>
<!--log4net配置end-->
</configuration>
4.LoggerHelper.cs
public class LoggerHelper
{
private static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo");
private static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror");
private static readonly log4net.ILog logmonitor = log4net.LogManager.GetLogger("logmonitor");
public static void Error(string ErrorMsg, Exception ex = null)
{
if (ex != null)
{
logerror.Error(ErrorMsg, ex);
}
else
{
logerror.Error(ErrorMsg);
}
}
public static void Info(string Msg)
{
loginfo.Info(Msg);
}
public static void Monitor(string Msg)
{
logmonitor.Info(Msg);
}
}