参考:https://github.com/NLog/NLog/wiki/Tutorial
步骤:
1. 使用Nuget安装NLog.Extensions.Logging
Install-Package NLog.Extensions.Logging
2.编写代码(到这步运行代码,不报错,但是也不会有log输出,因为没有设置配置文件)
3. 编写配置文件
在项目下新增加NLog.config 文件,并设置其能copy到运行目录。将一下内容粘到里面,重新运行程序就可以看到输出到file.txt的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="logfile" xsi:type="File" fileName="file.txt" />targets><rules><logger name="*" minlevel="Info" writeTo="logfile" />rules> nlog>
4. 增加输出源,将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="logfile" xsi:type="File" fileName="file.txt" /><target name="console" xsi:type="Console" />targets><rules><logger name="*" minlevel="Info" writeTo="logfile" /><logger name="*" minlevel="Info" writeTo="console" />rules> nlog>
5. 如果想发送邮件,可以安装NLog.MailKit
Install-Package NLog.MailKit
6.在配置文件中添加发送邮件的设置部分(参考https://github.com/nlog/NLog/wiki/Mail-target)
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"internalLogFile="d:Nlog_log.txt" internalLogLevel="Error"><variable name="smtpServer" value="***"/><variable name="smtpUserName" value="***"/><variable name="smtpPassword" value="***"/><variable name="from" value="***"/><variable name="to" value="***"/><targets><target name="logfile" xsi:type="File" fileName="logs${date:format=yyyyMMdd}_log.txt" layout="${date:format=yyyy-MM-dd HH:mm:ss} ${message}" /><target name="console" xsi:type="Console" layout="${date:format=yyyy-MM-dd HH:mm:ss} [${level}] ${message}"/><target name="infoMail" xsi:type="Mail"smtpServer="${smtpServer}"smtpUserName="${smtpUserName}"smtpPassword="${smtpPassword}"from="${from}"to="${to}"subject="info log"body="${message}"html="true"/><target name="errorMail" xsi:type="Mail"smtpServer="${smtpServer}"smtpUserName="${smtpUserName}"smtpPassword="${smtpPassword}"from="${from}"to="${to}"subject="error log"body="${message}"/>targets><rules><logger name="***" minlevel="Info" writeTo="infoMail" /><logger name="***" minlevel="Error" writeTo="logfile" /><logger name="Main" minlevel="Info" writeTo="console" /><logger name="Main" minlevel="Error" writeTo="errorMail" />rules><extensions><add assembly="NLog.MailKit"/>extensions> nlog>