1. 程式人生 > >ASP.NET Core 2.0系列學習筆記-NLog日誌配置檔案

ASP.NET Core 2.0系列學習筆記-NLog日誌配置檔案

一、新建ASP.NET Core 2.0 MVC專案,使用NuGet在瀏覽中搜索:NLog.Web.AspNetCore,如下圖所示:

二、在專案的bin\Debug\netcoreapp2.0\下新建一個xml型別的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="Warn"
      internalLogFile="internal-nlog.txt">

  <!--define various log targets-->
  <targets>

    <!--write logs to file-->
    <target xsi:type="File" name="allfile" fileName="nlog-all-${shortdate}.log"
                 layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />

    <target xsi:type="File" name="ownFile-web" fileName="nlog-my-${shortdate}.log"
                 layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" />

    <target xsi:type="Null" name="blackhole" />

  </targets>

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

    <!--Skip Microsoft logs and so log only own logs-->
    <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
  </rules>

</nlog>

三、在Startup類中新增配置,修改程式碼如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; //ILoggerFactory
using NLog.Extensions.Logging; //ConfigureNLog
using NLog.Web; //AddNLogWeb

namespace NETCoreNLog
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory
loggerFactory) { if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } loggerFactory.AddNLog(); //新增NLog app.AddNLogWeb(); loggerFactory.ConfigureNLog("nlog.config");//讀取Nlog配置檔案 app.UseStaticFiles(); //註冊wwwroot靜態檔案 //註冊MVC路由 app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }

注:檔案頭先引用 using Microsoft.Extensions.Logging;using NLog.Extensions.Logging;和using NLog.Web;

四、使用NLog日誌:

1.在Main方法中呼叫ConfigAndLog();

public static IConfigurationRoot Configuration { get; set; } //讀取指定json配置檔案
public static Logger nlog = LogManager.GetCurrentClassLogger(); //獲得日誌例項
public static void ConfigAndLog()
{
     var builder = new ConfigurationBuilder()
         .SetBasePath(Directory.GetCurrentDirectory())
         .AddJsonFile("appsettings.json");
     Configuration = builder.Build();
     string app_key = Configuration["appSettings:app_key"]; 
     string conn = Configuration["connectionStrings:conn"]; //讀取資料庫連線字串
     nlog.Debug($"資料庫連線為:{conn}"); //Nlog日誌使用   
}
public static void Main(string[] args)
{
    BuildWebHost(args).Run();
    ConfigAndLog();
}

2.在控制器IActionResult中使用Nlog

//獲得日誌的例項
public static Logger nlog = LogManager.GetCurrentClassLogger();
public IActionResult Index()
{
     nlog.Info("普通訊息日誌-----------");
     nlog.Debug("除錯日誌-----------");
     nlog.Error("錯誤日誌-----------");
     nlog.Fatal("異常日誌-----------");
     nlog.Warn("警告日誌-----------");
     nlog.Trace("跟蹤日誌-----------");
     nlog.Log(LogLevel.Warn, "Log日誌------------------");
     return View();
 }

注:NLog日誌的位置預設是在bin\Debug下面。

參考:http://www.voidcn.com/article/p-hukbuiwx-bch.html