步骤1:项目中加入NLOG库
打开“工具”->“NuGet包管理器”,搜索“NLOG”,安装“NLog”和“NLog.Windows.Forms”两个库,如下图所示
步骤2:添加引用
具体路径见下图
步骤3:增加NLog.config文件和NLog.xsd文件
可以从其它位置上COPY过来,也可以自己编写;NLog.config文件为LOG的配置文件,具体语法和意义见我的另一篇博文说明;
NLog.xsd是语法文件,不用改动
步骤4:在程序中增加引用
步骤5:设置config文件复制到输出目录
步骤6:使用
logger.Info("test");
得到输出,如下
完成!
附config文件
<?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"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<!-- optional, add some variables
https://github.com/nlog/NLog/wiki/Configuration-file#variables
-->
<variable name="myvar" value="myvalue"/>
<variable name="basedir" value="${specialfolder:folder=CommonApplicationData}/GRBL-Plotter" /> <!-- default, optional -->
<extensions>
<add assembly="NLog.Windows.Forms"/>
</extensions>
<!--
See https://github.com/nlog/nlog/wiki/Configuration-file
for information on customizing logging rules and outputs.
-->
<targets>
<!--
add your targets here
See https://github.com/nlog/NLog/wiki/Targets for possible targets.
See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
-->
<target name="file" xsi:type="File"
layout="${longdate} | ${pad:padding=-5:inner=${level}} | ${pad:padding=-30:inner=${logger}} | ${message}${exception:format=ToString}"
header="----- Possible levels: Trace, Debug, Info, Warn, Error, Fatal ----|
"
fileName="logfile.txt"
archiveFileName="logs/log_{#}.txt"
keepFileOpen="true"
maxArchiveFiles="20"
encoding="utf-8"
archiveNumbering="DateAndSequence"
archiveOldFileOnStartup="true"/>
<target xsi:type="RichTextBox" name="richTextBox" layout="${longdate} | ${pad:padding=-5:inner=${level}} | ${message}${exception:format=ToString}" controlName="rtbInfo" formName="ManualOpEx" />
<!--
Write events to a file with the date in the filename.
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
https://www.xin3721.com/Python/python13210.html
-->
<!--write log message to Visual Studio Output-->
<target name="debugger" xsi:type="Debugger" layout="NLog: ${date:format=HH\:mm\:ss} | ${level:uppercase=true:padding=-5} | ${message}" />
</targets>
<rules>
<!-- add your logging rules here -->
<logger name="*" minlevel="Debug" writeTo="file" />
<logger name="*" minlevel="Trace" writeTo="richTextBox"/>
<!--TRACE,DEBUG,INFO,WARN,ERROR,FATAL-->
<logger name="*" minlevel="Trace" writeTo="debugger" />
<!--
<logger name="*" minlevel="Debug" writeTo="file" />
Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace) to "f"
<logger name="*" minlevel="Debug" writeTo="f" />
-->
</rules>
</nlog>