天天看点

main方法 如何去掉http debug日志_Asp.NetCore Web开发之Nlog日志配置

    接着讲基于ASP .net Core 的web开发,这节主要讲一下如何使用和配置Nlog进行日志记录。

    日志在开发中的作用是很重要的,使用日志,程序出了错误可以及时捕获并记录下来,开发人员可以通过日志定位错误,进行修复。

    ASP .net Core虽然也给我们提供了一个原生的日志系统,但是这个日志系统不够强大,不能满足我们的一些需求,我们可以使用第三方的日志库,比较优秀的就是Nlog,使用它,我们首先要安装这个包,打开Nuget包管理器(了解详细的安装程序包请点击.Net Core平台下,添加包的引用),搜索:NLog.Web.AspNetCore 将其下载安装。

main方法 如何去掉http debug日志_Asp.NetCore Web开发之Nlog日志配置

    安装完成后,需要添加一个Nlog的xml配置文档:右键解决方案名,添加新项,如下图:

main方法 如何去掉http debug日志_Asp.NetCore Web开发之Nlog日志配置

    名字最好和图片一样,创建完成以后,将下方的配置代码复制到配置文件中:

<?xml version="1.0" encoding="http://www.nlog-project.org/schemas/NLog.xsd"      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">      type=            name="logfile"            fileName="${basedir}/logs/${shortdate}.log"            keepFileOpen="false"            layout="${longdate}|${callsite:fileName=True}                |${uppercase:${level}}|${message} ${exception}" />    type=            name="debugfile"            fileName="${basedir}/logs/${shortdate}_debug.log"            keepFileOpen="false"            layout="${longdate}|${callsite:fileName=True}                |${uppercase:${level}}|${message} ${exception}" />    type=            name="errfile"            fileName="${basedir}/logs/${shortdate}_error.log"            keepFileOpen="false"            layout="${longdate}|${callsite:fileName=True}            |${uppercase:${level}}|${message} ${exception}" />        "*" level=    "*" level=    "*" minlevel=  
           

    这个配置文件主要是配置日志规则,和存放日志文件的路径,有兴趣的同学可以去Nlog官网看一下配置文件的所有规则。

    注意,配置文件还有很重要的一步,右键配置文件点击属性:

main方法 如何去掉http debug日志_Asp.NetCore Web开发之Nlog日志配置

    将复制到输入目录设置为总是复制:

main方法 如何去掉http debug日志_Asp.NetCore Web开发之Nlog日志配置

    这样,当你运行或者打包程序的时候,这个日志配置文件也会被打包在内。

    接下来,我们要在Program.cs文件中配置使用Nlog,这个方法是用Nlog替代ASP.NetCore 自带的日志系统,也可以在Startup.cs中配置Nlog日志服务,两个方法都可以,先讲一下前者:

    在Main方法的生成主机方法之前加入:

//配置NlogNLogBuilder.ConfigureNLog("Nlog.config");
           

    这一步是加载配置文件,然后在CreateHostBuilder中添加几行配置:

.ConfigureLogging(l =>    {        //移除其余的Logger        l.ClearProviders();        //设置最低日志等级        l.SetMinimumLevel(LogLevel.Information);        //每次记录日志,都显示到控制台        l.AddConsole();    }).UseNLog()//使用Nlog
           

    最终配置如下图:

main方法 如何去掉http debug日志_Asp.NetCore Web开发之Nlog日志配置

    这样,我们就可以使用Nlog记录日志了:

main方法 如何去掉http debug日志_Asp.NetCore Web开发之Nlog日志配置

    运行一遍以后,会在运行目录下生成log文件夹,和两个日志文件(路径可以在配置文件中修改):

main方法 如何去掉http debug日志_Asp.NetCore Web开发之Nlog日志配置

    接下来讲一下第二种方法,注册Nlog日志服务,首先在appsetting.json中添加如下配置:

"NLog": {    "autoReload": true,    "throwConfigExceptions": true,    "internalLogLevel": "info",    "internalLogFile": "${basedir}/logs/internal-nlog.txt",    "extensions": {      "NLog.Extensions.Logging": {        "assembly": "NLog.Extensions.Logging"      }    },    "variables": {      "var_logdir": "${basedir}"    },    "default-wrapper": {      "type": "AsyncWrapper",      "overflowAction": "Block"    },    "targets": {      "all-file": {        "type": "File",        "fileName": "${var_logdir}/logs/nlog-all-${shortdate}.log",        "layout": {          "type": "JsonLayout",          "Attributes": [            {              "name": "time",              "layout": "${longdate}"            },            {              "name": "level",              "layout": "${level}"            },            {              "name": "target",              "layout": "${callsite:className=true:methodName=true:skipFrames=1}"            },            {              "name": "message",              "layout": "${message:raw=true}",              "escapeUnicode": "false"            },            {              "name": "properties",              "encode": "false",              "layout": {                "type": "JsonLayout",                "includeallproperties": "true"              }            }          ]        }      },      "own-console": {        "type": "LimitingWrapper",        "interval": "00:00:01",        "messageLimit": 100,        "target": {          "type": "Console",          "layout": "${longdate}|${event-properties:item=EventId_Id:whenEmpty=0}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|${callsite}"        }      }    },    "rules": [      {        "logger": "*",        "minLevel": "Trace",        "writeTo": "all-file"      },      {        "logger": "Microsoft.*",        "maxLevel": "Info",        "final": true      },      {        "logger": "*",        "minLevel": "Debug",        "writeTo": "own-console",        "filters": {          "whenRepeated": {            "layout": "${message}",            "action": "Ignore"          }        }      }    ]  }
           

    这个跟Nlog.config作用是一样的,然后在ConfigServices中注册服务:

//读取配置文件LogManager.Configuration= new NLogLoggingConfiguration(Configuration.GetSection("NLog"));var currentClassLogger = NLog.Web.NLogBuilder.ConfigureNLog(LogManager.Configuration).GetCurrentClassLogger();services.AddSingleton(currentClassLogger);
           

    然后在需要的地方正常添加依赖注入(NLog.Logger类):

main方法 如何去掉http debug日志_Asp.NetCore Web开发之Nlog日志配置

    这里要说明一点,通过这个方式配置的Nlog,是不会覆盖自带的日志系统的,如果要取消,可以在CreateHostBuilder中配置,怎么移除上方有讲。

    记录日志的方式如下:

_nlogger.Properties.Clear();_nlogger.Error("Read once Data");
           

    因为每次记录日志都会将属性值连带记录,它的属性值又是共有的,不清除的话,会有上次记录的冗余数据,这个当然是不友好的,所以要先清除,如果要记录额外数据的话,就可以为属性值赋值,它是一个键值对集合。

    本节到此结束...