zoukankan      html  css  js  c++  java
  • 使用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”会出现对应的日志文件

  • 相关阅读:
    UVa532 Dungeon Master 三维迷宫
    6.4.2 走迷宫
    UVA 439 Knight Moves
    UVa784 Maze Exploration
    UVa657 The die is cast
    UVa572 Oil Deposits DFS求连通块
    UVa10562 Undraw the Trees
    UVa839 Not so Mobile
    327
    UVa699 The Falling Leaves
  • 原文地址:https://www.cnblogs.com/jiao006/p/7652383.html
Copyright © 2011-2022 走看看