ASP.NET MVC 使用 NLog 记录日志
🏷️ Asp.NET MVC NLog
1. 安装 NLog 及相关包
powershell
Install-Package NLog
Install-Package NLog.Extended
Install-Package NLog.Web
2. 设置 NLog.config 配置文件
下面是官方 Demo 中的配置文件:
xml
<?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"
autoReload="true"
internalLogLevel="Trace"
internalLogFile="d:\work\log.txt">
<variable name="gmailUsername" value="${trim-whitespace:${file-contents:${basedir}/gmailusername.txt}}" />
<variable name="gmailPassword" value="${trim-whitespace:${file-contents:${basedir}/gmailpassword.txt}}" />
<extensions>
<!-- load NLog.Extended to enable ASP.NET-specific functionality -->
<add assembly="NLog.Extended" />
</extensions>
<!-- define various log targets -->
<targets>
<!-- write logs to file -->
<target xsi:type="File" name="file" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${aspnet-request:servervariable=URL} ${uppercase:${level}} ${message}" />
<!-- write log message to database -->
<target xsi:type="Database" name="db">
<!-- SQL command to be executed for each entry -->
<commandText>INSERT INTO [LogEntries](TimeStamp, Message, Level, Logger) VALUES(getutcdate(), @msg, @level, @logger)</commandText>
<!-- parameters for the command -->
<parameter name="@msg" layout="${message}" />
<parameter name="@level" layout="${level}" />
<parameter name="@logger" layout="${logger}" />
<!-- connection string -->
<dbProvider>System.Data.SqlClient</dbProvider>
<connectionString>server=.\SQLEXPRESS;database=MyLogs;integrated security=sspi</connectionString>
<!-- commands to install database -->
<install-command>
<text>CREATE DATABASE MyLogs</text>
<connectionString>server=.\SQLEXPRESS;database=master;integrated security=sspi</connectionString>
<ignoreFailures>true</ignoreFailures>
</install-command>
<install-command>
<text>
CREATE TABLE LogEntries(
id int primary key not null identity(1,1),
TimeStamp datetime2,
Message nvarchar(max),
level nvarchar(10),
logger nvarchar(128))
</text>
</install-command>
<!-- commands to uninstall database -->
<uninstall-command>
<text>DROP DATABASE MyLogs</text>
<connectionString>server=.\SQLEXPRESS;database=master;integrated security=sspi</connectionString>
<ignoreFailures>true</ignoreFailures>
</uninstall-command>
</target>
<!-- log message to event log -->
<target xsi:type="EventLog" name="eventLog" source="NLog Demo"
layout="${message}${newline}Call site: ${callsite:className=true:methodName=true}${newline}Logger: ${logger}">
</target>
<!-- increase the performance counter -->
<target xsi:type="PerfCounter" name="pc1" categoryName="My Log" counterName="My Counter">
</target>
<!-- send mail through GMail server -->
<target xsi:type="Mail"
name="mail"
smtpServer="smtp.gmail.com"
smtpPort="587"
enableSsl="true"
smtpAuthentication="Basic"
smtpUserName="${gmailUsername}"
smtpPassword="${gmailPassword}"
from="${gmailUsername}"
to="${gmailUsername}"
subject="NLogDemo logs"
addNewLines="true"
/>
<!-- send mail asynchronously, so that it does not block the calling thread -->
<wrapper-target xsi:type="AsyncWrapper" name="asyncMail">
<target-ref name="mail"/>
</wrapper-target>
<wrapper-target xsi:type="AspNetBufferingWrapper" name="allOutputs">
<wrapper-target xsi:type="PostFilteringWrapper">
<compound-target xsi:type="SplitGroup">
<target-ref name="file" />
<target-ref name="db" />
<target-ref name="eventLog" />
<target-ref name="pc1" />
<target-ref name="asyncMail" />
</compound-target>
<!-- during normal execution only log Info messages -->
<defaultFilter>level >= LogLevel.Info</defaultFilter>
<!-- if there is at least one error, log everything from trace level -->
<when exists="level >= LogLevel.Error" filter="level >= LogLevel.Trace" />
</wrapper-target>
</wrapper-target>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="allOutputs" />
</rules>
</nlog>
3. 使用 NLog 记录日志
更多使用示例可以参考 How to use structured logging 。
csharp
private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
logger.Info("test log");