WinForm(十四)窗体滚动日志

在桌面程序里,一般日志记录到文件里就可以了,但有的时间,也需要在窗体上动态滚动显示,这时,就需要引入日志框架了。

这里引入的依旧是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();

效果图:

WinForm(十四)窗体滚动日志