qiyadeng

专注于Java示例及教程
posts - 84, comments - 152, trackbacks - 0, articles - 34

不错的日志工具NLog

Posted on 2013-02-27 16:00 qiyadeng 阅读(5043) 评论(2)  编辑  收藏

在.net中也有非常多的日志工具,今天介绍下NLog。NLog特别好的地方就是和Vs(Visual Studio)开发环境的集成。

只需下载(下载地址)安装包,安装之后NLog就会在VS的新建项中增加很多选项,并且在编辑NLog配置文件时也会提供智能提示和校验。

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

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

vs add new item

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

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

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

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

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

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

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"

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

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

            keepFileOpen
="false" />

  </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();
  }
}

Feedback

# re: 不错的日志工具NLog  回复  更多评论   

2013-08-01 10:13 by 44
333

# re: 不错的日志工具NLog  回复  更多评论   

2013-08-01 10:13 by 44
343

只有注册用户登录后才能发表评论。


网站导航: