版權聲明:本文爲博主原創文章,未經博主容許不得轉載。數據庫
NLog是一款擁有豐富的途徑選擇和管理能力的可用於.net、Silverlight和Windows Phone的免費開源框架.它能夠將任何.net語言產生的調試信息轉化爲上下文信息(包括日期和時間,嚴重程度,進程,線程,環境信息),根據你喜愛的形式發送到一個或者多個目標存儲。那麼,咱們如何在一個應用程序上配置使用NLog,將日誌輸出到控制檯和文件?
首先,打開VS2012建立一個控制檯應用程序,添加NLog.dll引用。c#
接下來,開始配置NLog配置文件,NLog配置文件支持兩種方式:
1)是將配置寫到應用程序的配置文件(一般是applicationName.exe.config)或者Web.config文件中;
2)獨配置到一個文件,一般是NLog.config
這裏採用第一種方法,首先咱們須要在配置文件中增長以下形式的配置app
<configuration>
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<nlog>
</nlog>
</configuration>
<targets />
–定義日誌記錄輸出的目標位置,能夠配置爲輸出到控制檯,文件,數據庫,事件日誌等等<rules />
–定義日誌輸出路徑規則<extensions />
–定義從某個*.dll獲取Nlog擴展<include />
– 包含外部的配置文件<variable />
– 設置配置變量的值<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<nlog autoReload="true" internalLogLevel="Trace" internalLogFile="logs/internalLog.txt">
<targets>
<target name="t1" type="File" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${callsite} ${level}:
${message} ${event-context:item=exception} ${stacktrace} ${event-context:item=stacktrace}"/>
<target name="t2" type="Console" layout="${date:format=yyyyMMddHHmmss} ${callsite} ${level} ${message}"/>
</targets>
<rules>
<logger name="NLogConsoleExample" minlevel="Debug" maxlevel="Error" writeTo="t1,t2" />
</rules>
</nlog>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>