NLog

包引用

<PackageReference Include="NLog.Web.AspNetCore" Version="4.9.3" />

Program.cs

public class Program
{
    public static void Main(string[] args)
    {
        var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
        try
        {
            logger.Debug("init main");
            CreateHostBuilder(args).Build().Run();
        }
        catch (Exception exception)
        {
            //NLog: catch setup errors
            logger.Error(exception, "Stopped program because of exception");
            throw;
        }
        finally
        {
            // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
            NLog.LogManager.Shutdown();
        }
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            }).ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
            })
            .UseNLog();  // NLog: Setup NLog for Dependency injection;
}

nlog.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="Info"
      internalLogFile="c:\temp\internal-nlog.txt">

  <!-- enable asp.net core layout renderers -->
  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>

  <!-- the targets to write to -->
  <targets>
    <!-- write logs to file  -->
    <target xsi:type="File" name="allfile" fileName="c:\temp\nlog-all-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />

    <!-- another file log, only own logs. Uses some ASP.NET core renderers -->
    <target xsi:type="File" name="ownFile-web" fileName="c:\temp\nlog-own-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="allfile" />

    <!--Skip non-critical Microsoft logs and so log only own logs-->
    <logger name="Microsoft.*" maxlevel="Info" final="true" />
    <!-- BlackHole without writeTo -->
    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
  </rules>
</nlog>

 

配置minlevel没有起效果的问题

现象:配置minlevel为Trace,但是只能记录到Info+的

解决:先后的问题,在program.cs指定了如下配置

logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);

但是因为在startup.cs中使用appsettings.json中的配置进行了覆盖,所以实际上以appsettings.json为基准

这里需要注意appsettings.*.json的问题,如果在开发环境下,读取的是 appsettings.Development.json 文件中的配置,而他是折叠的,很容易忽略

附上相关配置

"Logging": {
  "LogLevel": {
    "Default": "Trace",
    "Microsoft": "Warning",
    "Microsoft.Hosting.Lifetime": "Information"
  }
},

另:可以将上面的代码完全移除,那么将以program.cs 中的配置为基准

自定义Target参考

using NLog;
using NLog.Common;
using NLog.Targets;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyAssembly
{
    [Target("AliYunLog")] //注意这里,这里是在Nlog.config中用到
    public class AliYunLogTarget : Target
    {
        AliyunHelp aL;
        public AliYunLogTarget()
        {
            aL = new AliyunHelp();
        }
        public string StoreName { get; set; }

        protected override void Write(LogEventInfo logEvent)
        {

            Dictionary<string, string> contents = new Dictionary<string, string>();
            // message 格式为 "xxx->abc|fff->123" 则进行处理
            if (logEvent.Message.IndexOf("|") >= 0)
            {
                var items = logEvent.Message.Split("|");
                for (int i = 0; i < items.Length; i++)
                {
                    var item = items[i];
                    var colonIndex = item.IndexOf("->");
                    if (colonIndex >= 0)
                    {
                        contents.Add(item.Substring(0, colonIndex), item.Substring(colonIndex + 2));
                    }
                    else
                    {
                        contents.Add($"message{i + 1}", item);
                    }
                }
            }
            else
            {
                contents.Add("message", logEvent.Message);
            }

            contents.Add("LoggerName", logEvent.LoggerName);
            contents.Add("Level", logEvent.Level.ToString());
            contents.Add("TimeStamp", logEvent.TimeStamp.ToString("yyyy-MM-dd HH:mm:ss:fff"));


            if (logEvent.StackTrace != null)
            {
                contents.Add("StackTrace", logEvent.StackTrace.ToString());
            }

            if (logEvent.Exception != null)
            {
                var error = logEvent.Exception.Message;
                var e = logEvent.Exception;
                while (e.InnerException != null)
                {
                    e = e.InnerException;
                    error += "|" + e.Message;
                }

                contents.Add("Exception", error);
            }

            // 这里将结果输入到日志记录的系统,如阿里日志
        }
    }
}

Nlog.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="Info" 
	  internalLogFile="c:\temp\internal-nlog.txt">
	<!-- 启用.net core的核心布局渲染器 -->
	<extensions>
		<add assembly="NLog.Web.AspNetCore" />
		<add assembly="MyAssembly" /><!-- 这里Target所在的程序集名 -->
	</extensions>
	<!-- 写入日志的目标配置 -->
	<targets>
		<!-- 调试  -->
		<target xsi:type="File" name="debug" fileName="logs/debug-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
		<!-- 警告  -->
		<target xsi:type="File" name="warn" fileName="logs/warn-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
		<!-- 错误  -->
		<target xsi:type="File" name="error" fileName="logs/error-${shortdate}.log" layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
		<!-- xsi:type="AliYunLog" 对应Target上指定的名称 -->
		<target xsi:type="AliYunLog" name="aliyun" storeName="storeName" />
	</targets>
	<!-- 映射规则 -->
	<rules>
		<logger name="*" minlevel="Trace" maxlevel="Fatal" writeTo="aliyun" />
		<!-- 调试  -->
		<logger name="*" minlevel="Trace" maxlevel="Debug" writeTo="debug" />
		<!--跳过不重要的微软日志-->
		<logger name="Microsoft.*" maxlevel="Info" final="true" />
		<!-- 警告  -->
		<logger name="*" minlevel="Info" maxlevel="Warn" writeTo="warn" />
		<!-- 错误  -->
		<logger name="*" minlevel="Error" maxlevel="Fatal" writeTo="error" />
	</rules>
</nlog>

一个使用字典的扩展

using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace NLog
{
    public static class LoggerExtentions
    {

        public static void LogInformation(this ILogger logger, Dictionary<string, string> contents, Exception exception, string message)
        {
            logger.Log( LogLevel.Information, contents, exception, message);
        }

        public static void LogInformation(this ILogger logger, Dictionary<string, string> contents, string message)
        {
            logger.LogInformation(contents, null, message);
        }

        public static void LogDebug(this ILogger logger, Dictionary<string, string> contents, Exception exception, string message)
        {
            logger.Log( LogLevel.Debug, contents, exception, message);
        }

        public static void LogDebug(this ILogger logger, Dictionary<string, string> contents, string message)
        {
            logger.LogDebug(contents, null, message);
        }

        public static void LogError(this ILogger logger, Dictionary<string, string> contents, Exception exception, string message)
        {
            logger.Log( LogLevel.Error, contents, exception, message);
        }

        public static void LogError(this ILogger logger, Dictionary<string, string> contents, string message)
        {
            logger.LogError(contents, null, message);
        }

        public static void LogWarning(this ILogger logger, Dictionary<string, string> contents, Exception exception, string message)
        {
            logger.Log( LogLevel.Warning, contents, exception, message);
        }

        public static void LogWarning(this ILogger logger, Dictionary<string, string> contents, string message)
        {
            logger.LogWarning(contents, null, message);
        }

        public static void LogTrace(this ILogger logger, Dictionary<string, string> contents, Exception exception, string message)
        {
            logger.Log(LogLevel.Trace, contents, exception, message);
        }

        public static void LogTrace(this ILogger logger, Dictionary<string, string> contents, string message)
        {
            logger.LogTrace(contents, null, message);
        }

        public static void Log(this ILogger logger, LogLevel level, Dictionary<string, string> contents, Exception exception, string message)
        {
            contents.Add($"$message", "message");
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(contents);

            logger.Log(level, exception, json);
        }

        public static void Log(this ILogger logger, LogLevel level, Dictionary<string, string> contents, string message)
        {
            logger.Log(level, contents, null, message);
        }
    }
}