使用NLog记录文本日志

 

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

 

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

 

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

 

第三步: 在项目目录下面创建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">

  <!-- 加载ASP.NET Core插件 -->
  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>

  <!-- 输出目的地 -->
  <targets>
    <!-- 输出到文件,这个文件记录所有日志 -->
    <target xsi:type="File" name="allfile" fileName="nlog-all-${shortdate}.log"
                layout="${longdate}|${event-properties:item=EventId.Id}|${logger}|${uppercase:${level}}|${message} ${exception}" />

    <!-- 另外一个日志记录文件,户口也跳过Microsoft开头相关日志信息 -->
    <target xsi:type="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}" />

    <!-- write to the void aka just remove -->
    <target xsi:type="Null" name="blackhole" />
  </targets>

  <!-- 写入目的地的规则 -->
  <rules>
    <!--全部记录,包括Microsoft开头的相关日志信息-->
    <logger name="*" minlevel="Trace" writeTo="allfile" />

    <!--跳过Microsoft开头的相关日志信息-->
    <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
    <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
  </rules>
</nlog>
View Code

 

第四步:修改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();
        }
    }
}
View Code

 

 

最后,在控制器调用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<ValuesController> _logger;

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



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

 

 

运行结果:

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

 

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

posted @ 2017-10-11 22:01  jiao006  阅读(1045)  评论(0编辑  收藏  举报