天天看点

NLog日志框架简写用法

NLog工作主要依赖的是两个文件一个是NLog.dll,另外一个是NLog.config,解下来演示下如何引入和进行配置

1.在你的项目中加入NLog。右击项目,选择添加新项目,选择Empty NLog Configuration,并选择添加(如图)。

NLog日志框架简写用法

(说明:有可能不像官网上说的在NLog的目录下面,在ASP.net Web项目中,会在VB的目录中。)

在非Asp.net项目中,记得把NLog.config文件复制到输出目录(右击NLog.config文件属性)。

NLog日志框架简写用法

2.编辑配置文件NLog.config.

关于配置文件如何编辑有大量的篇幅(https://github.com/nlog/nlog/wiki/Configuration-file),我们这里介绍两种常用的场景。

A)在Vs的输出窗口输出日志,关于这些变量的说明${},请参看文档Configuration Reference。(https://github.com/nlog/nlog/wiki)

B)以文件形式输出。

<target name="file" xsi:type="File" maxArchiveFiles="30"

            layout="${longdate} ${logger} ${message}"

            fileName="${basedir}/logs/log${shortdate}.txt"

            keepFileOpen="false" />

完整的配置文件例子:

<?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"  throwExceptions="true" internalLogFile="d:\internal_log_file.txt" internalLogLevel="Trace" internalLogToConsole="true">

  <targets>

    <target name="debugger" xsi:type="Debugger" layout="${logger}::${message}" />

    <target name="file" xsi:type="File" maxArchiveFiles="30"

  </targets>

  <rules>

    <logger name="*" minlevel="Trace" writeTo="debugger" />

    <logger name="*" minlevel="Trace" writeTo="file" />

  </rules>

</nlog>

3.在程序中使用NLog

在程序中使用就特别简单了,和大多数日志工具类似。

using NLog;

namespace MyNamespace

{

  public class MyClass

  {

    private static Logger logger = LogManager.GetCurrentClassLogger();

  }

}

继续阅读