首先创建一个config
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" /> </startup>
<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\LogError\" /> <param name="AppendToFile" value="true" /> <param name="MaxSizeRollBackups" value="100" /> <param name="MaxFileSize" value="10240" /> <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 %n异常级别:%-5p%n异常内容:%m%n" /> </layout> <!--< > = <> %n = 回车--> </appender> <appender name="InfoAppender" type="log4net.Appender.RollingFileAppender"> <param name="File" value="Log\LogInfo\" /> <param name="AppendToFile" value="true" /> <param name="MaxFileSize" value="10240" /> <param name="MaxSizeRollBackups" value="100" /> <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="日志时间:%d %n日志级别:%-5p %n日志内容:%m%n%n" /> </layout> </appender> </log4net>
</configuration>
在Properties-Assemblyinfo.cs中的最下方注册下日志
[assembly: log4net.Config.XmlConfigurator(ConfigFileExtension = "config", Watch = true)]
将代码复制在最下方,可以根据自己的需求更改配置
在需要使用的地方声明下log4net类
注:using log4net
loginfo = log4net.LogManager.GetLogger("loginfo");
在需要输出log的地方写上
loginfo.Info(info)
_________helper_______
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using log4net; namespace WindowsFormsApp1 { public class LogHelper { private LogHelper() {
}
public static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo");
public static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror");
public static void SetConfig() { log4net.Config.XmlConfigurator.Configure(); }
public static void SetConfig(FileInfo configFile) { log4net.Config.XmlConfigurator.Configure(configFile); }
public static void WriteLog(string info) { if (loginfo.IsInfoEnabled) { loginfo.Info(info); } }
public static void WriteLog(string info, Exception se) { if (logerror.IsErrorEnabled) { logerror.Error(info, se); } } } }