.Net Core學(xué)習(xí)教程之在Mvc中簡(jiǎn)單的使用日志組件
前言
本文是基于 .Net Core 2.0,只是蜻蜓點(diǎn)水,并非深入淺出。給大家介紹了關(guān)于.Net Core在Mvc中使用日志組件的相關(guān)內(nèi)容,分享出供大家參考學(xué)習(xí),下面話不多說(shuō)了,來(lái)一起看看詳細(xì)的介紹吧
目錄
使用內(nèi)置的日志組件
簡(jiǎn)單過(guò)渡到第三方組件 - NLog
使用內(nèi)置的日志
下面使用控制器 HomeController.cs 進(jìn)行演示。
需要 using Microsoft.Extensions.Logging;
方案一:
public class HomeController : Controller
{
private readonly ILogger _logger ;
public HomeController(ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger(typeof(HomeController));
}
}
方案二:
public class HomeController : Controller
{
private readonly ILogger _logger ;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
}
方案三:
public class HomeController : Controller
{
private readonly ILogger _logger ;
public HomeController(ILogger logger)
{
_logger = logger;
}
}
三種都是通過(guò)注入的方式獲取日志記錄器對(duì)象,在過(guò)去,我們會(huì)自己獨(dú)立封裝類似這些 Debug、Info 和 Error 等不同日志等級(jí)的方法,現(xiàn)在我們看看內(nèi)置的方法是如何使用的?
在 HomeController 內(nèi)添加 Index() 方法進(jìn)行測(cè)試。
public IActionResult Index()
{
_logger.LogDebug($"測(cè)試:{DateTime.Now.ToString(CultureInfo.InvariantCulture)}");
_logger.LogError($"測(cè)試:{DateTime.Now.ToString(CultureInfo.InvariantCulture)}");
_logger.LogInformation($"測(cè)試:{DateTime.Now.ToString(CultureInfo.InvariantCulture)}");
return Json(Guid.NewGuid());
}
在輸出結(jié)果中我們可以看到,不同日志的等級(jí)在控制臺(tái)中會(huì)以不同的顏色進(jìn)行標(biāo)注。
每種級(jí)別的 Log 都有多個(gè)方法重載,如 LogInformation() ,示例演示的代碼中使用的是比較簡(jiǎn)單一種,也就是最后一種。
//
// 摘要:
// Formats and writes an informational log message.
//
// 參數(shù):
// logger:
// The Microsoft.Extensions.Logging.ILogger to write to.
//
// eventId:
// The event id associated with the log.
//
// message:
// Format string of the log message.
//
// args:
// An object array that contains zero or more objects to format.
public static void LogInformation(this ILogger logger, EventId eventId, string message, params object[] args);
//
// 摘要:
// Formats and writes an informational log message.
//
// 參數(shù):
// logger:
// The Microsoft.Extensions.Logging.ILogger to write to.
//
// exception:
// The exception to log.
//
// message:
// Format string of the log message.
//
// args:
// An object array that contains zero or more objects to format.
public static void LogInformation(this ILogger logger, Exception exception, string message, params object[] args);
//
// 摘要:
// Formats and writes an informational log message.
//
// 參數(shù):
// logger:
// The Microsoft.Extensions.Logging.ILogger to write to.
//
// message:
// Format string of the log message.
//
// args:
// An object array that contains zero or more objects to format.
public static void LogInformation(this ILogger logger, string message, params object[] args);
其它細(xì)節(jié)以及詳情,或者希望使用其它日志組件可參考官方文檔:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?tabs=aspnetcore2x
簡(jiǎn)單過(guò)渡到第三方組件 - NLog
Nuget 安裝 NLog.Web.AspNetCore(目前 Nuget 最新為 4.4.1,但是官方的教程卻是 4.5 的,小編使用 4.4.1 進(jìn)行演示)。如需 4.5+ 可參考官方:https://github.com/NLog/NLog.Web/wiki/Getting-started-with-ASP.NET-Core-2

下面演示如何將內(nèi)置的組件簡(jiǎn)單的移植到 NLog 中。
先在根目錄創(chuàng)建配置文件 nlog.config,記得將屬性修改成始終復(fù)制到目錄:
<?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">
<!-- 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>
修改 Startup.cs 類中的 Configure() 方法,其它地方都不需要做出任何修改。
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddNLog(); //添加NLog
env.ConfigureNLog("nlog.config"); //讀取Nlog配置文件
//...
}

啟動(dòng)程序,你會(huì)發(fā)現(xiàn):

總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。
相關(guān)文章
使用Visual Studio編寫(xiě)單元測(cè)試
本文詳細(xì)講解了使用Visual Studio編寫(xiě)單元測(cè)試的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-03-03
.Net中的Junction Points(交接點(diǎn))操作
這篇文章介紹了.Net中的Junction Points(交接點(diǎn))操作,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06
Asp.net中處理一個(gè)站點(diǎn)不同Web應(yīng)用共享Session的問(wèn)題
Asp.net中處理一個(gè)站點(diǎn)不同Web應(yīng)用共享Session的問(wèn)題...2006-09-09
解決asp.net Sharepoint無(wú)法連接發(fā)布自定義字符串處理程序,不能進(jìn)行輸出緩存處理的方法
解決Sharepoint無(wú)法連接發(fā)布自定義字符串處理程序,不能進(jìn)行輸出緩存處理的方法2010-03-03
.NET6打包部署到Windows?Service的全過(guò)程
net用了這么久,雖然多數(shù)都是部署在centos系統(tǒng),但也有部署在windows上的情況,下面這篇文章主要給大家介紹了關(guān)于.NET6打包部署到Windows?Service的相關(guān)資料,需要的朋友可以參考下2022-10-10
asp.net URL重寫(xiě)簡(jiǎn)化版 速學(xué)URL重寫(xiě)
asp.net URL重寫(xiě)(URLRewriter)簡(jiǎn)化版 。速學(xué)URL重寫(xiě)2010-01-01
Asp.net開(kāi)發(fā)之webform圖片水印和圖片驗(yàn)證碼的實(shí)現(xiàn)方法
這篇文章主要介紹了Asp.net開(kāi)發(fā)之webform圖片水印和圖片驗(yàn)證碼的實(shí)現(xiàn)方法,實(shí)現(xiàn)思路分為前后臺(tái)代碼和效果展示,非常不錯(cuò)具有參考借鑒價(jià)值,需要的朋友可以參考下2016-10-10
Convert.ToInt32與Int32.Parse區(qū)別及Int32.TryParse
2個(gè)方法都可以把string轉(zhuǎn)換為int,那么他們有什么區(qū)別?什么時(shí)候該用什么?性能如何。 其實(shí)在2.0里還有Int32.TryParse也實(shí)現(xiàn)了同樣的效果。2009-01-01
asp.net導(dǎo)出excel的簡(jiǎn)單方法實(shí)例
這篇文章主要介紹了asp.net導(dǎo)出excel的簡(jiǎn)單方法實(shí)例,需要的朋友可以參考下2014-02-02

