天天看點

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");
           

    因為每次記錄日志都會将屬性值連帶記錄,它的屬性值又是共有的,不清除的話,會有上次記錄的備援資料,這個當然是不友好的,是以要先清除,如果要記錄額外資料的話,就可以為屬性值指派,它是一個鍵值對集合。

    本節到此結束...