天天看點

.net core 使用 NLog 記錄日志

一、先建立 .net core Web 應用程式

二、程式包控制台輸入以下指令行以安裝 Nuget 包:

install-package Nlog
install-package Nlog.Web.AspNetCore
           

三、添加配置檔案: 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="LogFiles/${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="Fatal" writeTo="blackhole" final="true" />-->
    <logger name="*" minlevel="Critical" writeTo="ownFile-web" />
  </rules>
</nlog>
           

四、修改 Startup.cs ,  其實除了引用之外, 也就是加兩行代碼而已:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using NLog.Web;

namespace WebApplication1
{
    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.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // 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.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            //使用NLog作為日志記錄工具
            loggerFactory.AddNLog();
            //引入Nlog配置檔案
            env.ConfigureNLog("nlog.config");

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
           

五、修改 Controller, 輸出日志:

private ILogger<HomeController> logger;

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

        public IActionResult Index()
        {
            logger.LogInformation("普通資訊日志-----------");
            logger.LogDebug("調試日志-----------");
            logger.LogError("錯誤日志-----------");
            logger.LogCritical("異常日志-----------");
            logger.LogWarning("警告日志-----------");
            logger.LogTrace("跟蹤日志-----------");
            logger.Log(LogLevel.Warning, "Log日志------------------");
            return View();
        }
           

日志級别:Trace -》Debug-》 Information -》Warning-》 Error-》 Critical

日志級别由小到大, Trace 就包含了所有日志。

如果想修改日志的輸出級别,應該在 nlog.config 中修改 minlevel="Trace"

試了一下, Critical 與 Fatal 的輸出是一緻的。

使用說明: https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2

詳細的配置參考: https://github.com/NLog/NLog/wiki/Configuration-file

中文配置文章: http://www.cnblogs.com/fuchongjundream/p/3936431.html

繼續閱讀