1.下載NLog和Nlog.config
2.配置NLog.asd
3.配置Nlog.config(本文爲SQL Server2017)
<?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"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<!-- optional, add some variables
https://github.com/nlog/NLog/wiki/Configuration-file#variables
-->
<variable name="myvar" value="myvalue"/>
<!--
See https://github.com/nlog/nlog/wiki/Configuration-file
for information on customizing logging rules and outputs.
-->
<targets>
<!--
add your targets here
See https://github.com/nlog/NLog/wiki/Targets for possible targets.
See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
-->
<!--
Write events to a file with the date in the filename.
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
-->
<!-- write logs to file -->
<target name="file" xsi:type="AsyncWrapper" queueLimit="5000" overflowAction="Discard">
<target xsi:type="File" fileName="${basedir}/logs/${shortdate}.log" layout="${longdate} ${level:uppercase=true} ${event-context:item=Action} ${message} ${event-context:item=Amount} ${stacktrace}" />
</target>
<!-- write log message to database -->
<target name="db" xsi:type="Database" connectionString="Data Source=數據庫名稱;Initial Catalog=ydqcx;Persist Security Info=True;User ID=sa;Password=密碼"
commandText="insert into tLog ([CreateDate], [Origin], [LogLevel], [Message], [StackTrace]) values (@createDate, @origin, @logLevel, @message, @stackTrace)">
<parameter name="@createDate" layout="${longdate}"/>
<!--日誌發生時間-->
<parameter name="@origin" layout="${callsite}"/>
<!--日誌來源-->
<parameter name="@logLevel" layout="${level}"/>
<!--日誌等級-->
<parameter name="@message" layout="${message}"/>
<!--日誌信息-->
<parameter name="@stackTrace" layout="${stacktrace}"/>
<!--堆棧信息-->
</target>
</targets>
<rules>
<!-- add your logging rules here -->
<!--
Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace) to "f"
<logger name="*" minlevel="Debug" writeTo="f" />
-->
<!--DEBUG,INFO,WARN,ERROR,FATAL-->
<logger name="*" minlevel="Info" writeTo="file"/>
<logger name="*" writeTo="db"/>
</rules>
</nlog>
4.建立數據庫表(當數據類型存儲數量小於正常所需存儲大小,數據庫存不上東西,所以設置爲varchar(Max))
5.引用,輸出
using NLog;
/////////////命名空間下///////////////////////////////////////////////
/// <summary>
/// 獲取log
/// </summary>
private ILogger log = LogManager.GetCurrentClassLogger();
//////////某方法下////////////////////////////
private void Login()
{
log.Info("用戶:" + user + "(登錄)");
//log.Fatal("用戶:" + user + "(登錄)");
}