.Net Core使用NLog記錄日誌

  參見:https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2git

大體步驟:github

  • Nuget中引用NLog及NLog.Web.AspNetCore 4.5+
  • 建立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="logs\internal-nlog.log">
    
      <!-- enable asp.net core layout renderers -->
      <extensions>
        <add assembly="NLog.Web.AspNetCore"/>
      </extensions>
    
      <!-- the targets to write to -->
      <targets>
        <!-- write logs to file  -->
        <target name="allFile" xsi:type="File" fileName="logs\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 name="ownFile" xsi:type="File" fileName="logs\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}" />
    
        <target name="blackHole" xsi:type="Null"  />
        
      </targets>
    
      <!-- rules to map from logger name to target -->
      <rules>
        <!--All logs, including from Microsoft-->
        <logger name="*" minlevel="Trace" writeTo="allFile" />
        <!--Own logs-->
        <logger name="HiP.*" minlevel="Trace" writeTo="ownFile" />
        
        <!--Skip non-critical Microsoft logs and so log only own logs-->
        <!--<logger name="Microsoft.*" maxLevel="Info" writeTo="blackHole" final="true" />-->
        
      </rules>
    </nlog>
    <!--LogLevel="Trace|Debug|Info|Warn|Error|Fatal"-->

     

  • 右鍵nlog.config,屬性,生成操做設爲「內容」,複製到輸出目錄爲「始終複製」
  • Program.cs中:
    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 ex)
                {
                    //NLog: catch setup errors
                    logger.Error(ex, "Stopped program because of exception");
                    throw ex;
                }
                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)
                 .UseServiceProviderFactory(new AutofacServiceProviderFactory())    //會調用Startup中的ConfigureContainer方法
                 .ConfigureWebHostDefaults(webBuilder =>
                 {
                     webBuilder
                       .UseStartup<Startup>()
                       .UseUrls("http://localhost:8080")
                       //這裏是配置log的
                       .ConfigureLogging((hostingContext, builder) =>
                       {
                           builder.ClearProviders();
                           //builder.SetMinimumLevel(LogLevel.Warning); //使用Nlogs的配置
                           //builder.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
                           //builder.AddConsole();
                           //builder.AddDebug();
                       })
                       .UseNLog(); // NLog: setup NLog for Dependency injection. 3.0中這樣添加
                 });
        }

     

  • 配置appsettings.json。注意在配置中的設置將覆蓋代碼中的SetMinimumLevel屬性。因此要麼刪除「Default」使用代碼中的配置,要麼就要設置正確。
    { "Logging": { "LogLevel": { "Default": "Trace", "Microsoft": "Information" } } }

    注意:如你有多個環境,注意appsetings.Development.json的配置。web

  • 使用:
using Microsoft.Extensions.Logging;

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

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }

    public IActionResult Index()
    {
        _logger.LogInformation("Index page says hello");
        return View();
    }
  • 結果查看。如你的配置與我一致,則在項目的logs文件夾會存在internal-nlog.txt文件。在bin\Debug\netcoreappXX\logs目錄下會以日期存在輸出日誌。
相關文章
相關標籤/搜索