[NLog] 日志配置与控件RichTextBox配置

(1)引用NLog和NLog.Windows.Forms

(2)配置app.config文件

 1 <configSections>    
 2     <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
 3   </configSections>
 4 
 5   <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd" autoReload="true">
 6     <targets>
 7       <target name="t1" xsi:type="File" fileName="${basedir}/logs/${shortdate}.log" layout="${longdate} - ${level:uppercase=true} - ${logger} - ${message}  ${exception:format=tostring}" />
 8       <target xsi:type="RichTextBox"
 9         name="textbox"
10         layout="${longdate} - ${level:uppercase=true} - ${logger} - ${message}  ${exception:format=tostring}"
11         autoScroll="true"
12         maxLines="100"
13         controlName="tbLogShow"
14         formName="MainForm"
15         useDefaultRowColoringRules="true"/>
16     </targets>
17     <rules>
18       <logger name="*" minlevel="Debug" maxlevel="Error" writeTo="t1" />
19       <logger name="*" minlevel="Debug" maxlevel="Error" writeTo="textbox" />
20     </rules>
21   </nlog>

(3)在确定控件对象生成以后(例如MainForm_Load里),再定义logger

1 private static ILogger _logger = null;
2 
3 private void MainForm_Load(object sender, EventArgs e)
4 {
5     if (_logger == null)
6        _logger = NLog.LogManager.GetCurrentClassLogger();           
7     }
8 }

ps:不添加NLog.Windows.Forms或未满足条件3,控件RichTextBox将不显示日志

原文地址:https://www.cnblogs.com/panpan-v1/p/8117720.html