.NET Core3.0 日志 logging的實(shí)現(xiàn)
多年的經(jīng)驗(yàn),日志記錄是軟件開發(fā)的重要組成部分。沒有日志記錄機(jī)制的系統(tǒng)不是完善的系統(tǒng)。在開發(fā)階段可以通過debug附件進(jìn)程進(jìn)行交互調(diào)試,可以檢測(cè)到一些問題,但是在上線之后,日志的記錄起到至關(guān)重要的作用。它可使我們?cè)谙到y(tǒng)出現(xiàn)問題之后,排查錯(cuò)誤提供依據(jù)。
.NET Core3.0內(nèi)置多種日志記錄程序,并且有第三方提供的日志記錄程序框架如:log4net,NLog,Serilog,elmah.io等。后面會(huì)介紹前三種日志框架如何與.NETcore3.0結(jié)合起來進(jìn)行使用。
內(nèi)置日志記錄提供程序
ASP.NETCore 提供以下提供程序:
- 控制臺(tái)-可以在控制臺(tái)查看日志輸出
- 調(diào)試-vs工具 -》開始調(diào)試-》輸出窗口進(jìn)行查看日志輸出
- EventSource-可使用PerfView 實(shí)用工具收集和查看日志
- EventLog-》僅在windows系統(tǒng)下可以使用事件查看器查看日志
- TraceSource
- AzureAppServicesFile
- AzureAppServicesBlob
- ApplicationInsights
創(chuàng)建使用日志
通用主機(jī)的應(yīng)用程序和非主機(jī)應(yīng)用程序使用的方式也是不同的。因?yàn)橥ㄓ弥鳈C(jī)內(nèi)部封裝了 依賴注入、logging、配置、IHostedService的實(shí)現(xiàn);并且默認(rèn)配置了控制臺(tái),調(diào)試,EventSource以及EventLog(僅當(dāng)在windows上運(yùn)行時(shí))提供程序。源碼如下
.ConfigureLogging((hostingContext, logging) => { var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); // IMPORTANT: This needs to be added *before* configuration is loaded, this lets // the defaults be overridden by the configuration. if (isWindows) { // Default the EventLogLoggerProvider to warning or above logging.AddFilter<EventLogLoggerProvider>(level => level >= LogLevel.Warning); } logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging")); logging.AddConsole(); logging.AddDebug(); logging.AddEventSourceLogger(); if (isWindows) { // Add the EventLogLoggerProvider on windows machines logging.AddEventLog(); } })
通用主機(jī)
添加提供程序
可自行選擇提供程序來替換默認(rèn)提供程序。在CreateHostBuilder時(shí)候 調(diào)用ClearProviders(),然后添加所需的提供程序。我們創(chuàng)建一個(gè)api項(xiàng)目為例
public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureLogging(logging => { logging.ClearProviders();//去掉默認(rèn)添加的日志提供程序 logging.AddConsole(); logging.AddDebug(); logging.AddEventSourceLogger(); logging.AddEventLog(); //logging.AddTraceSource(); }) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); })
創(chuàng)建日志
在 Web 應(yīng)用或托管服務(wù)中,由依賴關(guān)系注入 (DI) 獲取 ILogger。
private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; //可以顯示指定類別名稱ILoggerFactory logger //logger.CreateLogger("WebApi.Controllers.WeatherForecastController"); }
[HttpGet] public IEnumerable<WeatherForecast> Get() { //內(nèi)置日志 _logger.LogTrace(1000, "log Trace msg"); // _logger.LogDebug(1001, "log Debug msg"); // _logger.LogInformation(1002, "log Information msg"); // _logger.LogWarning(1003, "log Warning msg"); // _logger.LogError(1004, "log Error msg"); // _logger.LogCritical(1005, "log Critical msg"); //
非主機(jī)控制臺(tái)
添加提供程序
在創(chuàng)建 LoggerFactory 時(shí)調(diào)用提供程序的 Add{provider name} 擴(kuò)展方法:
var loggerFactory = LoggerFactory.Create(builder => { builder .AddFilter("Microsoft", LogLevel.Warning) .AddFilter("System", LogLevel.Warning) .AddFilter("LoggingConsoleApp.Program", LogLevel.Debug) .AddConsole() .AddEventLog(); });
創(chuàng)建日志
在非主機(jī)控制臺(tái)應(yīng)用中,使用 LoggerFactory 來創(chuàng)建 ILogger。
ILogger logger = loggerFactory.CreateLogger<Program>(); logger.LogInformation("非主機(jī)模式輸出log message");·
運(yùn)行輸出
第三方日志框架
log4net,NLog和Serilog這3種日志記錄框架幾乎在.NET空間中占主導(dǎo)地位,不需要太多介紹。看看最近6周的下載排名就知道了。如圖
log4net 在NET Core 3.0使用
引用Log4net到項(xiàng)目中,安裝NuGet包
Install-Package log4net -Version 2.0.8
在項(xiàng)目中添加log4net.config文件,右鍵改文件屬性-》復(fù)制到輸出目錄選擇-》始終復(fù)制
<log4net> <appender name="RollingFile" type="log4net.Appender.RollingFileAppender"> <file value="loglog4net.log" /> <appendToFile value="true" /> <maximumFileSize value="50KB" /> <maxSizeRollBackups value="2" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date %level %message%newline" /> </layout> </appender> <root> <level value="ALL" /> <appender-ref ref="RollingFile" /> </root> </log4net>
在Startup文件中添加log4net配置的文件
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseLog4net(); /// <summary> /// 使用log4net配置 /// </summary> /// <param name="app"></param> /// <returns></returns> public static IApplicationBuilder UseLog4net(this IApplicationBuilder app) { var logRepository = log4net.LogManager.CreateRepository(Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy)); log4net.Config.XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config")); return app; } 上面兩步的準(zhǔn)備完成之后,在Controllers中使用 private readonly ILog log; public WeatherForecastController(ILogger<WeatherForecastController> logger) { this.log = LogManager.GetLogger(typeof(WeatherForecastController)); } [HttpGet] public IEnumerable<WeatherForecast> Get() { //第三方日志 log.Error("log4net erro msg"); //log4net
運(yùn)行查看日志文件
NLog 在NET Core 3.0使用
引用NLog到項(xiàng)目中,安裝NuGet包
Install-Package NLog.Web.AspNetCore -Version 4.9.0 Install-Package NLog -Version 4.6.7
添加配置文件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="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="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="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>
在Program.cs文件配置 Main方法添加
NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
CreateHostBuilder方法添加
.UseNLog() //NLog: Setup NLog for Dependency injection
使用
[HttpGet] public IEnumerable<WeatherForecast> Get() { //內(nèi)置日志 _logger.LogTrace(1000, "log Trace msg"); // _logger.LogDebug(1001, "log Debug msg"); // _logger.LogInformation(1002, "log Information msg"); // _logger.LogWarning(1003, "log Warning msg"); // _logger.LogError(1004, "log Error msg"); // _logger.LogCritical(1005, "log Critical msg"); //
Serilog 在NET Core 3.0使用
引用Serilog到項(xiàng)目中,安裝NuGet包
Install-Package Serilog.AspNetCore -Version 3.1.0
在Program.cs文件進(jìn)行Logger初始化
Main方法添加
Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .WriteTo.Console()// 配置日志輸出到控制臺(tái) .WriteTo.File("logserilog.txt", rollingInterval: RollingInterval.Day) //配置日志輸出文件,生成周期每天 .CreateLogger(); try { Log.Information("Starting up"); CreateHostBuilder(args).Build().Run(); } catch (Exception ex) { Log.Fatal(ex, "Application start-up failed"); } finally { Log.CloseAndFlush(); }
運(yùn)行輸出:
小結(jié):本文主要講解NET Core3.0內(nèi)置的日志提供程序和與第三方日志框架(Log4net,Nlog,Serilog)的使用。
到此這篇關(guān)于.NET Core3.0 日志 logging的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān).NET Core3.0 日志 logging內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- .net core日志結(jié)構(gòu)化
- .net core 使用阿里云分布式日志的配置方法
- ASP.NET Core擴(kuò)展庫(kù)之Http日志的使用詳解
- ASP.NET Core擴(kuò)展庫(kù)之日志功能的使用詳解
- .NET Core下使用Log4Net記錄日志的方法步驟
- Asp.Net Core用NLog記錄日志操作方法
- .NET Core開發(fā)日志之OData(Open Data Protocol)
- .NET Core日志配置的方法
- 詳解.Net Core中的日志組件(Logging)
- .Net Core項(xiàng)目如何添加日志功能詳解
- 詳解.Net core2.0日志組件Log4net、Nlog簡(jiǎn)單性能測(cè)試
- .net core日志系統(tǒng)相關(guān)總結(jié)
相關(guān)文章
文本框中輸入小寫字母即時(shí)轉(zhuǎn)換為大寫實(shí)現(xiàn)思路
系統(tǒng)中有一個(gè)文本框,要求輸入大寫字母,只是用戶不是那么配合所以只好在程序來控制了,感興趣的朋友可以參考下哈2013-03-03asp.net中通過DropDownList的值去控制TextBox是否可編寫的實(shí)現(xiàn)代碼
Web窗體上有兩控件,DropDownList1,TextBox1,當(dāng)DropDownList的值選擇是YES的時(shí)候,TextBox1可編輯,當(dāng)選擇NO的時(shí)候,TextBox1的值為空,并且不能編輯,該如何實(shí)現(xiàn)2012-11-11CKEditor與dotnetcore實(shí)現(xiàn)圖片上傳功能
這篇文章主要為大家詳細(xì)介紹了CKEditor與dotnetcore實(shí)現(xiàn)圖片上傳功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-09-09淺談ASP.NET Core 2.0 帶初始參數(shù)的中間件(譯)
這篇文章主要介紹了淺談ASP.NET Core 2.0 帶初始參數(shù)的中間件(譯),非常具有實(shí)用價(jià)值,需要的朋友可以參考下2017-10-10C#圖片截取壓縮(百分比壓縮/大小壓縮)實(shí)現(xiàn)代碼
為了娛樂寫了個(gè)截取圖片和壓縮圖片你的小工具:按照百分比壓縮/制定大小壓縮等等,感興趣的朋友可以了解下啊,希望本文對(duì)你學(xué)些c#圖片知識(shí)有所幫助2013-01-01.NET6?ConfigurationManager的實(shí)現(xiàn)及使用方式
這篇文章主要介紹了.NET6?ConfigurationManager的實(shí)現(xiàn),我們上面展示的這一部分的ConfigurationManager代碼,其實(shí)就是替代了原來的ConfigurationBuilder類的功能,需要的朋友可以參考下2021-12-12