使用NLog记录文本日志


本文主要介绍如何在 .Net Core 2.0 框架下面使用Nlog。

第一步:创建一个Net Core项目,我这里选用的是WebAPI,项目名称叫 NlogTest 。

第二步:添加 NLog,NLog.Web.AspNetCore 两个Nuget包。在安装的时候,勾选“包括与发行版”,安装最新的版本。

第三步: 在项目目录下面创建nlog.config文件,文件内容如下

<?xml version="1.0" encoding="utf-8" ?>
"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">

  
  
    "NLog.Web.AspNetCore"/>
  

  
  
    
    "File" name="allfile" fileName="nlog-all-${shortdate}.log"
                layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" />

    
    "File" name="ownFile-web" fileName="nlog-own-${shortdate}.log"
            layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|  ${message} ${exception}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />

    
    "Null" name="blackhole" />
  

  
  
    
    "*" minlevel="Trace" writeTo="allfile" />

    
    "Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
    "*" minlevel="Trace" writeTo="ownFile-web" />
  

第四步:修改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;
using Microsoft.Extensions.Options;
using NLog.Web;
using NLog.Extensions.Logging;

namespace NlogTest
{
    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.UseDeveloperExceptionPage();
            }


            loggerFactory.AddNLog();//添加NLog
            env.ConfigureNLog("nlog.config");//读取Nlog配置文件

            app.UseMvc();
        }
    }
}

最后,在控制器调用NLog的记录日志方法

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

namespace NlogTest.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        private readonly ILogger _logger;

        public ValuesController(ILogger logger)
        {
            _logger = logger;
        }



        // GET api/values
        [HttpGet]
        public IEnumerable<string> Get()
        {
            _logger.LogInformation("Index page says hello");
            return new string[] { "value1", "value2" };
        }
    }
}

运行结果:

如果调用日志报错,会出现 internal-nlog.txt

如果运行成功,“bin-->debug-->netcoreapp2.0”会出现对应的日志文件