NLog-ASP.NET Core 5入门

1、创建一个新的ASP.NET Core项目

在Visual Studio 2019中。需要版本16.8+

2、手动或使用NuGet在csproj中添加依赖项

安装最新版本:

  • NLog.Web.AspNetCore 4.9+

  • 如有可能,更新NLog软件包

在csproj中:

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

3、创建一个nlog.config文件。

在项目的根目录中创建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="System.Net.Http.*" maxlevel="Info" final="true" /> <!-- BlackHole without writeTo -->


    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
  </rules>
</nlog>

请注意,如果删除所有其他LoggingProviders(如控制台)并且仅使用NLog,则可能必须特别注意Hosting Lifetime Startup Messages。因为这可能导致托管环境(Visual Studio / Docker / Azure容器)看不到已启动的应用程序。

4、更新program.cs

更新program.cs

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using NLog.Web;


namespace ASP.NET_Core_5_NLog_Example
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var logger = 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)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
                .ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    logging.SetMinimumLevel(LogLevel.Trace);
                })
                .UseNLog();  // NLog: Setup NLog for Dependency injection
    }
}

5、配置appsettings.json / appsettings.Development.json

中指定的日志记录配置appsettings.json会覆盖对的任何调用SetMinimumLevel。因此"Default":,请根据您的需要删除或正确调整它。

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Trace",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

切记还要更新任何特定于环境的配置,以免引起任何意外。前任appsettings.Development.json

6、写日志

将ILogger注入您的控制器中:

using Microsoft.Extensions.Logging;


public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;


    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
        _logger.LogDebug(1, "NLog injected into HomeController");
    }


    public IActionResult Index()
    {
        _logger.LogInformation("Hello, this is the index!");
        return View();
    }


7、示例输出

启动ASP.NET Core网站时,我们得到两个文件:

2020-12-29 16:47:02.5291||DEBUG|ASP.NET_Core_5_NLog_Example.Program|init main |url: |action: 
2020-12-29 16:47:03.5943|1|DEBUG|ASP.NET_Core_5_NLog_Example.Controllers.HomeController|NLog injected into HomeController |url: https://localhost/|action: Index
2020-12-29 16:47:03.5943||INFO|ASP.NET_Core_5_NLog_Example.Controllers.HomeController|Hello, this is the index! |url: https://localhost/|action: Index
2020-12-29 16:47:02.5291||DEBUG|ASP.NET_Core_5_NLog_Example.Program|init main 
2020-12-29 16:47:03.5260||INFO|Microsoft.Hosting.Lifetime|Application started. Press Ctrl+C to shut down. 
2020-12-29 16:47:03.5260||INFO|Microsoft.Hosting.Lifetime|Hosting environment: Development 
2020-12-29 16:47:03.5260||INFO|Microsoft.Hosting.Lifetime|Content root path: D:\nlog\NLog.Web\examples\ASP.NET Core 5\ASP.NET Core 5 NLog Example 
2020-12-29 16:47:03.5943|1|DEBUG|ASP.NET_Core_5_NLog_Example.Controllers.HomeController|NLog injected into HomeController 
2020-12-29 16:47:03.5943||INFO|ASP.NET_Core_5_NLog_Example.Controllers.HomeController|Hello, this is the index!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值