我了个去

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

本文转载:http://www.blogjava.net/qiyadeng/archive/2013/02/27/395799.html

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

 

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

 

官方网站:http://nlog-project.org/download/

配置文件的使用:
http://www.cnblogs.com/fuchongjundream/p/3936431.html

NLog使用很方便,可以使用单独的配置文件,分别在winform 、console、windows service、 web 上使用。无需在app.config、和web.config配置文件中配置。

本文测试的DEMO地址:https://files.cnblogs.com/zfanlong1314/NlogConfig.zip
 
 

 

posted on 2016-07-08 15:41  Robert123456  阅读(451)  评论(0编辑  收藏  举报