在桌面程序里,一般日志記錄到文件里就可以了,但有的時間,也需要在窗體上動態滾動顯示,這時,就需要引入日志框架了。
這里引入的依舊是NLog(在我的Mini API系統里,用的也是NLog)。首先要從Nuget中引入NLog.Windows.Forms,然后添加NLog.config,設置“始終復制”。
<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>WinExe</OutputType><TargetFramework>net7.0-windows</TargetFramework><Nullable>enable</Nullable><UseWindowsForms>true</UseWindowsForms><ImplicitUsings>enable</ImplicitUsings></PropertyGroup><ItemGroup><PackageReference Include="NLog.Windows.Forms" Version="4.6.0" /></ItemGroup><ItemGroup><None Update="NLog.config"><CopyToOutputDirectory>Always</CopyToOutputDirectory></None></ItemGroup></Project>
下面是NLog的配置文件,有兩個Target和兩個Rules,第一個Target是基于RichTextBox控件的,也是在一個窗體中,放置一個RichTextBox控件,來滾動顯示輸出的日志,所以在這個Target配置中設置的有窗體的名字和這個RichTextBox控件的名字。
第二個是基于文件的,也就是日志不僅顯示在UI上,還同時寫一份到文件里,以便后查。(關于NLog框加的學習,請參考官網https://nlog-project.org)
<?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 xsi:type="RichTextBox"name="richTextBoxLog"layout="${longdate}|${level:uppercase=true}|${logger}|${message}"height="30"autoScroll="true"maxLines="100"showMinimized="true"toolWindow="true"controlName="LogRichTextBox"formName="LogForm"width="50"useDefaultRowColoringRules="true"allowAccessoryFormCreation="true"messageRetention="None" supportLinks="false">????</target><target name="logfile" xsi:type="File" fileName="${basedir}/logs/${date:format=yyyyMMdd}.txt" /></targets><rules><logger name="*" minlevel="Debug" writeTo="richTextBoxLog" /><logger name="*" minlevel="Debug" writeTo="logfile" /></rules>
</nlog>
下面是窗體寫了一個擴展方法,擴展了7個方法,當然可以按照自己需求進行擴展。另外,如果你在一些非窗體的類中寫日志,也可以參照進行擴展。
public static class LoggerExpand
{public static void LogInfo(this Form form, string message){_logger.Info(message);}public static void LogTrace(this Form form, string message){_logger.Trace(message);}public static void LogError(this Form form, string message){_logger.Error(message);}public static void LogDebug(this Form form, string message){_logger.Debug(message);}public static void LogFatal(this Form form, string message){_logger.Fatal(message);}public static void LogWarn(this Form form, string message){_logger.Warn(message);}public?static?void?Log(this?Form?form,?LogLevel?level,?string?message){_logger.Log(level, message);}static Logger _logger => LogManager.GetCurrentClassLogger();
}
本例設置的日志動態滾動顯示窗體是獨立的桌面,并不在主窗體中,所以在彈出日志窗體時,需要ReInitialize一下日志控件,如下第2行代碼,否則RichTextBox不會顯示日志。
var??_logForm?=?new?LogForm();
RichTextBoxTarget.ReInitializeAllTextboxes(_logForm);
_logForm.Show();
效果圖: