參考:https://github.com/NLog/NLog/wiki/Tutorial 步驟: 1. 使用Nuget安裝NLog.Extensions.Logging 2.編寫代碼(到這步運行代碼,不報錯,但是也不會有log輸出,因為沒有設置配置文件) 3. 編寫配置文件 在項目下新增加NLog ...
參考: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>