欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.net core 2.1 Nlog.Web.AspNetCore Nlog日志

程序员文章站 2023-12-31 21:16:46
1、先创建 .net core Web 应用程序,选择API 2、安装 Nuget 包:Nlog.Web.AspNetCore install-package Nlog install-package Nlog.Web.AspNetCore 或者打开Nuget管理界面搜索Nlog.Web.AspNe ......

1、先创建 .net core web 应用程序,选择api

.net core 2.1 Nlog.Web.AspNetCore Nlog日志

 

 

 .net core 2.1 Nlog.Web.AspNetCore Nlog日志

 

 

 

2、安装 nuget 包:nlog.web.aspnetcore

install-package nlog
install-package nlog.web.aspnetcore

或者打开nuget管理界面搜索nlog.web.aspnetcore(我安装的版本是v4.9.0)

.net core 2.1 Nlog.Web.AspNetCore Nlog日志

3、添加配置文件: nlog.config  

.net core 2.1 Nlog.Web.AspNetCore 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="info"
      internallogfile="c:\temp\internal-nlog.txt">

  <!-- enable asp.net core layout renderers -->
  <extensions>
    <add assembly="nlog.web.aspnetcore"/>
  </extensions>

  <!-- the targets to write to -->
  <targets>
    <!-- write logs to file  -->
    <target xsi:type="file" name="allfile" filename="c:\temp\nlog-all-${shortdate}.log"
            layout="${longdate}|${event-properties:item=eventid_id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />

    <!-- another file log, only own logs. uses some asp.net core renderers -->
    <target xsi:type="file" name="ownfile-web" filename="c:\temp\nlog-own-${shortdate}.log"
            layout="${longdate}|${event-properties:item=eventid_id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <!--all logs, including from microsoft-->
    <logger name="*" minlevel="trace" writeto="allfile" />

    <!--skip non-critical microsoft logs and so log only own logs-->
    <logger name="microsoft.*" maxlevel="info" final="true" /> <!-- blackhole without writeto -->
    <logger name="*" minlevel="trace" writeto="ownfile-web" />
  </rules>
</nlog>

.net core 2.1 Nlog.Web.AspNetCore Nlog日志

配置appsettings.json

 "logging": {
    "loglevel": {
      "default": "trace",
      "microsoft": "information"
    }
  }

4、注册日志依赖

方法一:通过修改program.cs

//需引用
//using microsoft.extensions.logging;
//using nlog.web;
 
public class program
    {
        public static void main(string[] args)
        {
            nlog.web.nlogbuilder.configurenlog("nlog.config");
            createwebhostbuilder(args).build().run();
        }

        public static iwebhostbuilder createwebhostbuilder(string[] args) =>
            webhost.createdefaultbuilder(args)
                .usestartup<startup>()
                .configurelogging(logging =>
                 {
                     logging.clearproviders(); //移除已经注册的其他日志处理程序
                     logging.setminimumlevel(microsoft.extensions.logging.loglevel.trace); //设置最小的日志级别
                 })
                 .usenlog();
    }

方法二:通过修改startup.cs里的configure函数

//需引用
//using nlog.extensions.logging;
//using nlog.web;

public void configure(iapplicationbuilder app, ihostingenvironment env, iloggerfactory loggerfactory)
        {
            if (env.isdevelopment())
            {
                app.usedeveloperexceptionpage();
            }
            else
            {
                app.usehsts();
            }

            app.usehttpsredirection();

            loggerfactory.addnlog();//添加nlog
            env.configurenlog("nlog.config");//读取nlog配置文件

          
            app.usemvc();
        }

5、修改 controller, 输出日志:

 

  [route("api/")]
    public class logincontroller : controller
    {
        private ilogger<logincontroller> logger;
         public logincontroller(ilogger<logincontroller> _logger)
        {
             logger = _logger;
          }


        [route("login")]
        [httpget]
        public stringlogin()
        {
            logger.loginformation("info日志");
            logger.logerror("error日志");
            logger.logwarning("warning日志");
            logger.logcritical("critical日志");
            logger.logwarning("warning日志");
            logger.logtrace("trace日志");
            logger.log(loglevel.warning, "logwarn日志");
            logger.log(loglevel.debug, "logdebug日志");
            logger.log(loglevel.error, "logerror日志");
            return "";
        }
}     

 

打印日志的时候有两种方式

 logger.log(loglevel.warning, "logwarning日志:"); //标红的地方可以选择日志的级别 

 logger.logwarning("warning日志");//直接调内置的级别函数

6、结果

.net core 2.1 Nlog.Web.AspNetCore Nlog日志

 程序跑起来之后会出现前两个文件~访问完接口后会出现最后那个文件

internal-nlog 记录了nlog的启动及加载config的信息。
nlog-all 记录了所有日志
nlog-own 记录了我们自定义的日志

 7、修改配置

 打开官方提供的nlog.config  配置参考 https://github.com/nlog/nlog/wiki/configuration-file

子节点<target>  配置参考 

属性layout表示输出文本格式 配置参考 

子节点<rule>  日志的路由表  顺序是从上往下 一个<logger>就是一个路由信息

日志级别:trace >debug> information >warn> error> fatal
<logger>属性:
name - 日志源/记录者的名字 (允许使用通配符*) minlevel : 匹配日志范围的最低级别 maxlevel : 匹配日志范围的*别 level : 单一日志级别 levels : 一系列日志级别,由逗号分隔 writeto : 日志应该被写入的目标,由逗号分隔,与target的你name对应 final : 为true标记当前规则为最后一个规则。其后的logger不会运行

附最后的配置文档

<?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"
    >


  <!-- the targets to write to -->
  <targets>
    <!-- write logs to file  -->
    <target xsi:type="file" name="allfile" filename="log\${shortdate}-all.log"
            layout="${longdate} | ${event-properties:item=eventid_id:whenempty=0} | ${uppercase:${level}}|${logger} |${message} ${exception:format=tostring}" />

    <!-- another file log, only own logs.uses some asp.net core renderers -->
    <target xsi:type="file" name="errorfile" filename="log\${shortdate}-error.log"
            layout="${longdate} | ${event-properties:item=eventid_id:whenempty=0} | ${uppercase:${level}} | ${logger} | ${message} ${exception:format=tostring} | url: ${aspnet-request-url} | action: ${aspnet-mvc-action} | ${callsite}" />

    <target xsi:type="file" name="taskfile" filename="log\${shortdate}-warn.log"
            layout="${longdate} | ${event-properties:item=eventid_id:whenempty=0} | ${uppercase:${level}} | ${logger} | ${message} ${exception:format=tostring} | url: ${aspnet-request-url} | action: ${aspnet-mvc-action} | ${callsite}" />

    <target xsi:type="file" name="runfile" filename="log\${shortdate}-info.log"
            layout="${longdate} | ${event-properties:item=eventid_id:whenempty=0} | ${uppercase:${level}} | ${logger} | ${message} ${exception:format=tostring} | url: ${aspnet-request-url} | action: ${aspnet-mvc-action} | ${callsite}" />

  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <!--all logs, including from microsoft-->
    <logger name = "*" minlevel="trace" writeto="allfile" />
    <!--skip non-critical microsoft logs and so log only own logs-->
    <logger name = "*" levels="error,warn,critical" writeto="errorfile" />
    <logger name = "*" level="info" writeto="taskfile" />
    <logger name = "*" level="warn" writeto="runfile" final="true"/>

  </rules>
</nlog>

 

参考github: 

 




 

 

上一篇:

下一篇: