首页 > 代码库 > NLog日志使用方法

NLog日志使用方法

Nlog是一款可以通过自动化配置来把log信息指定写入 win console,Sql server,甚至是通过STMP 发送邮件的log engine

首先下载Nlog DLL,通过网上直接download 或者nuget 下载DLL都可以。

http://nlog-project.org/download/

然后把下载下来的Nlog.dll ,Nlog,extension.dll 加入项目reference.


我暂时只加载了Nlog,因为还没去研究Nlog.extension有什么功能。

之后就是配置文件了,(Nlog Configuration), 它其实是一个 config文件Name:(Nlog.config

格式如下:

01<?xml version="1.0" encoding="utf-8" ?>
02<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
03      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
04 
05  <!--
06  See http://nlog-project.org/wiki/Configuration_file
07  for information on customizing logging rules and outputs.
08   -->
09  <targets>
10    <!-- add your targets here -->
11     
12    <!--
13    <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
14            layout="${longdate} ${uppercase:${level}} ${message}" />
15    -->
16  </targets>
17 
18  <rules>
19    <!-- add your logging rules here -->
20     
21    <!--
22    <logger name="*" minlevel="Trace" writeTo="f" />
23    -->
24  </rules>
25</nlog>

或者如果你是WebAPP的话,可以把config直接写在web.config的<configuration>节点下,我比较喜欢这种

<configuration>
  <configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
  </configSections>
  <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <!--  See http://nlog-project.org/wiki/Configuration_file  for information on customizing logging rules and outputs.   -->
    <targets>
      <target xsi:type="File" name="f" fileName="${basedir}/APP_Data/logs/${shortdate}.log" layout="${longdate} ${uppercase:${level}} ${message}" /> 
    </targets>
    <rules>
      <logger name="*" minlevel="Trace" writeTo="f" />
    </rules>
  </nlog>

</configuration>



接下来就是比较有技术含量的东西了,如何把log写入数据库,或者发邮件通知,也是通过配置文件,配置如下:

<?xml version="1.0" encoding="utf-8" ?>
02<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
03      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
04   
05  <!--nlog debug start-->
06  <!--<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
07        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
08        throwExceptions="true" internalLogFile="c:\nlog.txt" internalLogLevel="Debug" autoReload="true">-->
09  <!--nlog debug end-->
10   
11  <!--
12  See http://nlog-project.org/wiki/Configuration_file
13  for information on customizing logging rules and outputs.
14   -->
15  <targets>
16    <!-- add your targets here -->
17 
18    <!--<target xsi:type="File" name="f" fileName="${basedir}/App_Data/logs/${shortdate}.log"
19            layout="${longdate} ${uppercase:${level}} ${message}" />-->
20 
21    <target xsi:type="File" name="f" fileName="${basedir}/App_Data/logs/${shortdate}.log"
22            layout="${longdate} ${uppercase:${level}} ${loginuser} ${message} ${machinename} ${exception:format=type} ${callsite:className=true} ${logger} ${exception:stacktrace} ${exception:format=tostring}" />
23 
24    <target xsi:type="Database" name="db"  dbProvider="mssql" commandText="Insert into NLog_Record(time_stamp, level, host, url, type, source, logger, message, stacktrace, detail, loginuser) Values(@time_stamp, @level, @host, @url, @type, @source, @logger, @message, @stacktrace, @detail, @loginuser);" connectionString="Data Source=localhost;Initial Catalog=Log_DB;Persist Security Info=True;User ID=資料庫登入帳號;Password=資料庫登入密碼;">
25      <!--<parameter name="@time_stamp" layout="${longdate}" />-->
26      <parameter name="@time_stamp" layout="${date:format=yyyy\-MM\-dd HH\:mm\:ss.fff} " />
27      <parameter name="@level" layout="${level}" />
28      <parameter name="@host" layout="${machinename}" />
29      <parameter name="@url" layout="${aspnet-request:serverVariable=url}" />
30      <parameter name="@type" layout="${exception:format=type}" />
31      <parameter name="@source" layout="${callsite:className=true}" />
32      <parameter name="@logger" layout="${logger}" />
33      <parameter name="@message" layout="${message}" />
34      <parameter name="@stacktrace" layout="${exception:stacktrace}" />
35      <parameter name="@detail" layout="${exception:format=tostring}" />
36      <parameter name="@loginuser" layout="${loginuser}" />
37    </target>
38 
39    <target xsi:type="Mail" name ="FatalMail"
40            smtpServer="smtp.gmail.com"
41            smtpPort="587"
42            smtpAuthentication="Basic"
43            smtpUsername="你要寄出的Email帳號"
44            smtpPassword="寄出Email的密碼"
45            enableSsl="true"
46            addNewLines="true"
47            from="寄出的Email"
48            to="收信的Email,收信的Email2"
49            subject="${machinename} 於 ${shortdate} ${time} Log級別:${level} 於 ${callsite:className=true}, 出現 ${exception:format=type}!"
50            header="========================================================================="
51            body="${newline}
52                  發生時間:${longdate} ${newline}${newline}
53                  Log等級:${level:uppercase=true} ${newline}${newline}
54                  Logger:${logger} ${newline}${newline}
55                  Source:${callsite:className=true} ${newline}${newline}
56                  使用者:${loginuser} ${newline}${newline}
57                  Exception類別:${exception:format=type} ${newline}${newline}
58                  錯誤訊息:${message} ${newline}${newline}"
59            footer="========================================================================="
60        />
61 
62    <target bufferSize="5" name="ErrorMail" xsi:type="BufferingWrapper">
63      <target xsi:type="Mail"
64              smtpServer="smtp.gmail.com"
65              smtpPort="587"
66              smtpAuthentication="Basic"
67              smtpUsername="你要寄出的Email帳號"
68              smtpPassword="寄出Email的密碼"
69              enableSsl="true"
70              addNewLines="true"
71              from="寄出的Email"
72              to="收信的Email,收信的Email2"
73              subject="${machinename} 於 ${shortdate} ${time} Log級別:${level} 出現錯誤!"
74              header="========================================================================="
75              body="${newline}
76                    發生時間:${longdate} ${newline}${newline}
77                    Log等級:${level:uppercase=true} ${newline}${newline}
78                    Logger:${logger} ${newline}${newline}
79                    Source:${callsite:className=true} ${newline}${newline}
80                    使用者:${loginuser} ${newline}${newline}
81                    Exception類別:${exception:format=type} ${newline}${newline}
82                    錯誤訊息:${message} ${newline}${newline}"
83              footer="========================================================================="
84            />
85    </target>
86 
87  </targets>
88 
89  <rules>
90    <!-- add your logging rules here -->
91 
92    <logger name="*" maxlevel="Info" writeTo="f" />
93    <logger name="*" minlevel="Warn" writeTo="db" />
94    <logger name="*" level="Fatal" writeTo="FatalMail" />
95    <logger name="*" level="Error" writeTo="ErrorMail" />
96 
97  </rules>
98</nlog>

需要注意的是,配置文件的

<target> 存放log的地方,文件          /数据库/邮件

<rule>    是写入/显示log的方式 

最后就是Nlog的语句了:

using NLog;

        private static Logger logger = LogManager.GetCurrentClassLogger();
        public ActionResult Index()
        {
            logger.Trace("Sample trace message");
            logger.Debug("Sample debug message");
            logger.Info("Sample informational message");
            logger.Warn("Sample warning message");
            logger.Error("Sample error message");
            logger.Fatal("Sample fatal error message");


            // alternatively you can call the Log() method 
            // and pass log level as the parameter.
            logger.Log(LogLevel.Info, "Sample informational message");


如果你写入的是consoleApp,你会发现不同的log颜色会不同,一目了然