在我們的日常開發過程中log的輸出是必不可少且至關重要的工作,能夠將log明確的輸出有助於我們快速定位並解決相關問題,該篇文章主要介紹一下如何使用Log4Net根據log level的不同將log輸出到不同的檔案中,主要是將error級別的log和其他級別的log進行分離輸出,這樣我們可以在特定的檔案中看到全部的error資訊。
第一步:首先通過log4net.config檔案來定義log4net配置資訊:
<?xml version="1.0" encoding="UTF-8"?>
<log4net>
<root>
<level value="DEBUG" />
<!--<level value="INFO" />-->
<!-- 預先定義兩種appender型別,LogFileAppender型別用來定義普通log的輸出,
HighLevelFileLogAppender型別用來定義Error級別的log的輸出-->
<appender-ref ref="LogFileAppender" />
<appender-ref ref="HighLevelFileLogAppender" />
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<param name="File" value="Logs\CommonSolution_.log" />
<param name="AppendToFile" value="true" />
<rollingStyle value="Composite" />
<maximumFileSize value="5MB" />
<!--<param name="DatePattern" value="yyyy-MM-dd".log""/>-->
<param name="DatePattern" value="yyyy-MM-dd" />
<param name="StaticLogFileName" value="false" />
<maxSizeRollBackups value="5" />
<preserveLogFileNameExtension value="true" />
<encoding value="UTF-8" />
<layout type="log4net.Layout.PatternLayout">
<header value="Level DateTime Version Thread Class EventID- Message 
" />
<param name="ConversionPattern" value="%-5level %date{MM-dd HH:mm:ss,fff} %property{Version} %thread %logger %property{EventID}- %message %newline" />
</layout>
<!--新增log輸出的過濾規則,輸出的最小log級別為DEBUG,最大log級別為WARN-->
<filter type="log4net.Filter.LevelRangeFilter">
<levelMin value="DEBUG" />
<levelMax value="WARN" />
</filter>
</appender>
<appender name="HighLevelFileLogAppender" type="log4net.Appender.RollingFileAppender">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<param name="File" value="Logs\CommonSolution_" />
<param name="AppendToFile" value="true" />
<param name="DatePattern" value="yyyy-MM-dd"-High.log"" />
<param name="StaticLogFileName" value="false" />
<rollingStyle value="Composite" />
<maximumFileSize value="5MB" />
<maxSizeRollBackups value="5" />
<encoding value="UTF-8" />
<layout type="log4net.Layout.PatternLayout">
<header value="Level DateTime Version Thread Class EventID- Message 
" />
<param name="ConversionPattern" value="%-5level %date{MM-dd HH:mm:ss,fff} %property{Version} %thread %logger %property{EventID}- %message %newline" />
</layout>
<filter type="log4net.Filter.LevelRangeFilter">
<!--新增log輸出的過濾規則,輸出的最小log級別為ERROR,最大log級別為ERROR-->
<levelMin value="ERROR"/>
<levelMax value="ERROR"/>
</filter>
</appender>
</log4net>
複製程式碼
第二步:封裝一個簡單的LogHelper類,用來管理Log物件的建立:
using log4net;
using log4net.Config;
using log4net.Repository;
using System;
using System.Collections.Concurrent;
using System.IO;
namespace CommonSolution.Util.Log
{
public class LogHelper
{
public static ILoggerRepository logRepository { get; set; }
private const string RepositoryName = "NetCoreRepository";
private static readonly ConcurrentDictionary<Type, ILog> Loggers = new ConcurrentDictionary<Type, ILog>();
public static void InitLogger(string filePath)
{
logRepository = LogManager.CreateRepository(RepositoryName);
XmlConfigurator.Configure(logRepository, new FileInfo(filePath));
}
/// <summary>
/// 動態修改log檔案的儲存地址
/// </summary>
/// <param name="folder">要儲存log檔案的儲存地址</param>
/// <param name="fileName">要儲存的log檔案的name</param>
public static void UpdateLogStoreFolder(string folder, string fileName)
{
var storedPath = LogManager.GetRepository(RepositoryName);
var appenders = storedPath.GetAppenders();
if (appenders == null) return;
foreach (var app in appenders)
{
if (app.Name.Equals("LogFileAppender") || app.Name.Equals("HighLevelFileLogAppender"))
{
var ra = app as RollingFileAppender;
ra.File = Path.Combine(folder, fileName + "-");
ra.ActivateOptions();
}
}
}
public static ILog GetLogger(Type source)
{
ILog log;
if (!Loggers.TryGetValue(source, out log))
{
log = LogManager.GetLogger(RepositoryName, source);
Loggers.TryAdd(source, log);
}
return log;
}
}
}複製程式碼
第三步:在工程中使用LogHelper來完成log的輸出,以.Net Core工程為例子,我們首先需要在工程的Startup.cs中呼叫LogHelper中的InitLogger方法初始化log4net,方法引數為log4net.config配置檔案路徑:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
var logFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Configuration.GetValue<string>("Log4NetFile"));
LogHelper.InitLogger(logFilePath);
}
複製程式碼
第四步:在程式中輸出log:
public class HomeController : Controller {
private readonly ILog _log = LogHelper.GetLogger(typeof(HomeController));
public IActionResult Index()
{
_log.Warn("This is Warn Message");
_log.Debug("This is Debug Message");
_log.Info("This is Info Message");
_log.Error("This is Error Message");
return View();
}
}複製程式碼
輸出結果如圖所示:
這樣我們就完成了根據log level的不同將log輸出到不同的檔案中的全部工作,希望能為大家的實際開發帶來幫助。