Step1、将Log4net.config放到指定的目录下
Step2、在App.config中添加日志记录开关IsWriteLog以及Log4net.config的相对路径
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="IsWriteLog" value="1" />
<add key="log4net" value="配置\\log4net.config" />
</appSettings>
<!--<appSettings>
</appSettings>-->
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>
Step3、在程序的program类的Main方法中添加以下代码
static void Main()
{
//初始化日志文件
string state = System.Configuration.ConfigurationManager.AppSettings["IsWriteLog"];
//判断是否开启日志记录
if (state == "1")
{
var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + ConfigurationManager.AppSettings["log4net"];
var fi = new System.IO.FileInfo(path);
LogHelper.SetConfig(fi);
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
Step4、添加LogHelper类
class LogHelper
{
public static readonly log4net.ILog loginfo = log4net.LogManager.GetLogger("loginfo");
public static readonly log4net.ILog logerror = log4net.LogManager.GetLogger("logerror");
private static object thisLock = new object();
public static readonly log4net.ILog logwarn = log4net.LogManager.GetLogger("logwarn");
public static void SetConfig(FileInfo configFile)
{
log4net.Config.XmlConfigurator.Configure(configFile);
}
public static void WriteLog_Warn(string info, bool realWriteLog = true)
{
lock (thisLock)
{
if (realWriteLog)
{
if (logwarn.IsInfoEnabled)
{
logwarn.Warn (info);
}
}
}
}
public static void WriteLog(string info, bool realWriteLog = true)
{
lock (thisLock)
{
if (realWriteLog)
{
if (loginfo.IsInfoEnabled)
{
loginfo.Info(info);
}
}
}
}
public static void WriteLog(string info, Exception se, bool realWriteLog = true)
{
lock (thisLock)
{
if (realWriteLog)
{
if (logerror.IsErrorEnabled)
{
logerror.Error(info, se);
}
}
}
}
/// <summary>
/// 日志保留多少天
/// </summary>
/// <param name="logFilePath"></param>
/// <param name="saveDays"></param>
public static void SaveLogDays(string logFilePath, int saveDays)
{
lock (thisLock)
{
string[] logFileName = Directory.GetFiles(logFilePath);
if (logFileName.Count() > saveDays)
{
File.Delete(logFileName[0]);
}
}
}
}
Step5、log4net.config的内容如下
c
Step6、调用
LogHelper.WriteLog("日志");
LogHelper.WriteLog_Warn("日志警告");
需要引用System.Configuration