nlog 配置

Posted zhuwansu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了nlog 配置相关的知识,希望对你有一定的参考价值。

using NLog;
using NLog.Config;
using NLog.Targets;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dben.CommonLib
{
    public static class NLogDefaultConfig
    {
        public static void InitNlogInfo()
        {
            const string layout = @"${date:format=HH\:mm\:ss}[${logger}]${message}";

            var consoleTarget = new ColoredConsoleTarget()
            {
                Layout = layout
            };

            var fileTarget = new FileTarget()
            {
                FileName = "${basedir}/logs/${logger}/${shortdate}.txt",
                Layout = layout
            };

            var config = new LoggingConfiguration();
            config.AddTarget("console", consoleTarget);
            config.AddTarget("file", fileTarget);

            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, consoleTarget));
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, fileTarget));

            LogManager.Configuration = config;
        }
    }
}
<?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:\LogFiles\nlog.internal.log.txt">
  
  <!--<variable name="gmailUsername" value="${trim-whitespace:${file-contents:${basedir}/gmailusername.txt}}" />
  <variable name="gmailPassword" value="${trim-whitespace:${file-contents:${basedir}/gmailpassword.txt}}" />-->

  <!-- define various log targets -->
  <targets>
    <!-- write logs to file -->
    <target xsi:type="File" name="file" fileName="D:\LogFiles\${logger}\${shortdate}.log"
            layout="${longdate} ${aspnet-request:servervariable=URL} ${uppercase:${level}} ${message}" />
   </targets>

  <rules>
    <logger name="*" minlevel="Trace" writeTo="file" />
  </rules>
</nlog>

二选一

以上是关于nlog 配置的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 NLog 记录到多个目标?

NLog插入数据库异常处理

Nlog日志出坑合集

NLog的介绍使用

NLog写入Mongo日志配置

NLOG配置