本文转载: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,并选择添加(如图)。

(说明:有可能不像官网上说的在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();
}
}