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

 

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

 

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

使用NLog记录文本日志

 

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

相关文章:

  • 2021-06-07
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-19
  • 2022-12-23
  • 2021-10-05
猜你喜欢
  • 2021-05-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-23
  • 2022-02-09
相关资源
相似解决方案