目錄
一、NLog 簡介
NLog是適用於各種.NET平台的靈活,免費的日志記錄平台。NLog使寫入多個目標變得容易 。(數據庫,文件,控制台)並即時更改日志記錄配置。(本文主要介紹寫日志到文件中)
- Nlog 官網:https://nlog-project.org/
- Nlog 配置說明:https://nlog-project.org/config/
- Nlog Github Wiki:https://github.com/NLog/NLog/wiki
注:以下操作為 asp.net core web項目,編輯器為VS2019
二、NLog 安裝
2.1 使用程序包管理控制台(Package Manager)
PM> Install-Package NLog
2.2 .Net CLI
dotnet add package NLog
在項目的根目錄下,在cmd窗口中輸入上面的命令即可安裝。
三. NLog 配置
3.1 Nlog配置方式
- 通過配置文件;
- 通過程序代碼;
3.2 通過配置文件配置Nlog
- 在項目的根目錄創建Nlog.config文件,並設置文件屬性:
- 具體配置
下面的配置,就是一個簡單的配置Nlog.config的demo,將下面的配置復制到Nlog.config中,即可將日志寫入到PsTest.log文件中。
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<targets>
<target name="file" xsi:type="File"
fileName="${basedir}\PsTest.log"
layout="${longdate} | ${level:uppercase=true}: ${message} | ${stacktrace}"
maxArchiveFiles="3"
archiveAboveSize="10240"
encoding="utf-8"/>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="file"></logger>
</rules>
</nlog>
下面簡單介紹下各配置項的意思:
targets 節點中定義了一系列日志輸出目標,每一個輸出目標是一個 target 元素。
target標簽:
- fileName 屬性:指日志寫入的文件的路徑及文件名。${basedir}指應用的當前路徑。
- layout 屬性:設置每條日志的輸出內容及格式。${longdate} 指寫入日志的時間,${level}指日志等級, ${stacktrace}指堆棧信息。
- archiveAboveSize 屬性:設置日志文件的大小的最大值,單位為byte,如果下條日志寫入的話要超出這個值,就會新建個日志文件,繼續寫入。
- maxArchiveFiles 屬性:指該target的日志文件最多允許產生的個數,通常與archiveAboveSize 屬性配合使用。
rules 節點是日志路由規則的集合,由一個或多個 logger 元素組成。每個 logger 元素記錄了 logger 的名字、目標輸出以及要處理的日志等級。
logger標簽:
- name 屬性:設置命名空間和類,如果為*,代表針對所有程序集。
- minlevel 屬性:指只有當日志等級大於"Debug"時,才會寫入。
- writeTo 屬性:指輸出目標,與target的name對應。
四、程序代碼中寫日志
public static void Main(string[] args)
{
var i = 100;
while (i > 1)
{
NlogTest();
i--;
}
}
public static void NlogTest()
{
//通過NLog.LogManager.GetCurrentClassLogger方法可以創建一個與所在類同名(包括 namespace)的 NLog.Logger 的實例。
var logger = LogManager.GetCurrentClassLogger();
logger.Error("something Error!");
logger.Info("something Info!");
logger.Debug("something Debug!");
try
{
List<int> ls = null;
var c = ls.Count;
}
catch (Exception ex)
{
logger.Error(ex.Message);
}
}
來到應用的生成目錄下面即可看到PsTest.log日志文件。
可以看到生成了多個log文件,因為配置文件設置的log文件最大為10k。
打開PsTest.0.log文件:
日志已經按照配置的格式寫入到文件中!
但這樣寫有個問題,就是每次寫日志都要先創建一個NLog.Logger 的實例,這樣的話,如果程序集較多,就造成了代碼冗余,所以,還是封裝一個Nlog的幫助類比較好,每次都調用這個類去寫日志
- 封裝的nlog幫助類:
public class PsLog
{
public static void Error(Exception ex)
{
Exception iex = GetInnerException(ex);
Error(iex.ToString());
}
public static void Error(string msg)
{
WriteLog(msg, LogLevel.Error);
}
private static void WriteLog(string msg, LogLevel level)
{
try
{
if (LogLevel.Debug == level)
{
LogManager.GetCurrentClassLogger().Debug(msg);
}
else if (LogLevel.Error == level)
{
LogManager.GetCurrentClassLogger().Error(msg);
}
else if (LogLevel.Fatal == level)
{
LogManager.GetCurrentClassLogger().Fatal(msg);
}
else if (LogLevel.Info == level)
{
LogManager.GetCurrentClassLogger().Info(msg);
}
else if (LogLevel.Trace == level)
{
LogManager.GetCurrentClassLogger().Trace(msg);
}
else if (LogLevel.Warn == level)
{
LogManager.GetCurrentClassLogger().Warn(msg);
}
else
{
LogManager.GetCurrentClassLogger().Info(msg);
}
}
catch (System.Exception e)
{
try
{
string strPath = Directory.GetCurrentDirectory();
using (FileStream fs = File.Open(strPath + @"\fatal.txt", FileMode.OpenOrCreate))
using (StreamWriter sw = new StreamWriter(fs))
sw.WriteLine(DateTime.Now.ToString() + ": Can not write the nlog, " + e.Message);
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
public static void Info(string msg)
{
WriteLog(msg, LogLevel.Info);
}
private static Exception GetInnerException(Exception ex)
{
if (ex.InnerException == null)
{
return ex;
}
return GetInnerException(ex.InnerException);
}
}
- 調用幫助類:
public static void NlogTest()
{
PsLog.Error("something Error!");
PsLog.Info("something Info!");
PsLog.Debug("something Debug!");
try
{
List<int> ls = null;
var c = ls.Count;
}
catch (Exception ex)
{
PsLog.Error(ex);
}
}