首先在项目中添加NuGet包
在AssemblyInfo.cs文件中添加[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4net.config", ConfigFileExtension = "config", Watch = true)]
在bin\Debug目录下会看到有log4net的两个文件,然后需要创建一个log4net的配置文件,可以创建个文本文档后另存为所有文件.config获得
用文本文档打开配置文件输入
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="System.Configuration.IgnoreSectionHandler"/>
</configSections>
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="Logging\logfile.log"/>
<appendToFile value="true"/>
<rollingStyle value="Composite"/>
<datePattern value="yyyyMMdd"/>
<maxSizeRollBackups value="10"/>
<maximumFileSize value="50MB"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level - %message%newline"/>
</layout>
</appender>
<root>
<level value="All"/>
<appender-ref ref="RollingLogFileAppender"/>
</root>
</log4net>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2"/>
</startup>
</configuration>
最后再创建一个AppLog.cs的类
using log4net;
using log4net.Config;
using System;
using System.IO;
using System.Windows.Forms;
namespace DLPrinter.Common {
public class AppLog {
private static readonly ILog log;
static AppLog() {
XmlConfigurator.ConfigureAndWatch(new FileInfo(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile));
log = LogManager.GetLogger(typeof(AppLog));
}
public static void Debug(object message) {
log.Debug(message);
}
public static void DebugFormatted(string format, params object[] args) {
log.DebugFormat(format, args);
}
public static void Info(object message) {
log.Info(message);
}
public static void InfoFormatted(string format, params object[] args) {
log.InfoFormat(format, args);
}
public static void Warn(object message) {
log.Warn(message);
}
public static void Warn(object message, Exception exception) {
log.Warn(message, exception);
}
public static void WarnFormatted(string format, params object[] args) {
log.WarnFormat(format, args);
}
public static void Error(object message) {
log.Error(message);
}
public static void Error(object message, Exception exception) {
log.Error(message, exception);
}
public static void ErrorFormatted(string format, params object[] args) {
log.ErrorFormat(format, args);
}
public static void Fatal(object message) {
log.Fatal(message);
}
public static void Fatal(object message, Exception exception) {
log.Fatal(message, exception);
}
public static void FatalFormatted(string format, params object[] args) {
log.FatalFormat(format, args);
}
}
}
在其他代码中想在日志输出就可以直接调用AppLog.Debug("");