您好,登錄后才能下訂單哦!
小編給大家分享一下.NET Core下如何使用Log4Net記錄日志,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
Log4Net
相信大家都很熟悉了,算是比較主流和著名的日志組件了。
官網: logging.apache.org
開源地址: https://github.com/apache/logging-log4net
最佳實踐
在項目中添加組件包
Install-Package log4net
添加 log4net.config
文件
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <log4net debug="false"> <appender name="info" type="log4net.Appender.RollingFileAppender,log4net"> <param name="File" value="log4net/info/" /> <param name="AppendToFile" value="true" /> <param name="MaxSizeRollBackups" value="-1"/> <param name="MaximumFileSize" value="5MB"/> <param name="RollingStyle" value="Composite" /> <param name="DatePattern" value="yyyyMMdd\\HH".log"" /> <param name="StaticLogFileName" value="false" /> <layout type="log4net.Layout.PatternLayout,log4net"> <param name="ConversionPattern" value="%n { "system": "Meowv.Blog", "datetime": "%d", "description": "%m", "level": "%p", "info": "%exception" }" /> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <levelMin value="INFO" /> <levelMax value="INFO" /> </filter> </appender> <appender name="error" type="log4net.Appender.RollingFileAppender,log4net"> <param name="File" value="log4net/error/" /> <param name="AppendToFile" value="true" /> <param name="MaxSizeRollBackups" value="-1"/> <param name="MaximumFileSize" value="5MB"/> <param name="RollingStyle" value="Composite" /> <param name="DatePattern" value="yyyyMMdd\\HH".log"" /> <param name="StaticLogFileName" value="false" /> <layout type="log4net.Layout.PatternLayout,log4net"> <param name="ConversionPattern" value="%n { "system": "Meowv.Blog", "datetime": "%d", "description": "%m", "level": "%p", "info": "%exception" }" /> </layout> <filter type="log4net.Filter.LevelRangeFilter"> <levelMin value="ERROR" /> <levelMax value="ERROR" /> </filter> </appender> <root> <level value="ALL"></level> <appender-ref ref="info"/> <appender-ref ref="error"/> </root> </log4net> </configuration>
控制臺項目
using log4net; using log4net.Config; using System; using System.IO; using System.Reflection; namespace ConsoleAppDemo { class Program { static void Main(string[] args) { var log4netRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(log4netRepository, new FileInfo("log4net.config")); ILog log = LogManager.GetLogger(log4netRepository.Name, "NETCorelog4net"); log.Info("NETCorelog4net log"); log.Info("test log"); log.Error("error"); log.Info("linezero"); Console.ReadKey(); } } }
AspNetCore項目
新建一個靜態類,寫一個擴展方法 UseLog4Net()
,用于 log4net
初始化。
public static class Log4NetExtensions { public static IHostBuilder UseLog4Net(this IHostBuilder hostBuilder) { var log4netRepository = LogManager.GetRepository(Assembly.GetEntryAssembly()); XmlConfigurator.Configure(log4netRepository, new FileInfo("log4net.config")); return hostBuilder; } }
擴展方法返回 IHostBuilder
對象,這樣可以鏈式調用,美化代碼,然后在 Program.cs
中使用擴展方法 UseLog4Net()
。
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace WebAppDemo { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }).UseLog4Net(); } }
配置完成,然后在任意地方寫入日志即可。
using log4net; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; namespace WebAppDemo.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILog _log; public WeatherForecastController() { _log = LogManager.GetLogger(typeof(WeatherForecastController)); } [HttpGet] public IEnumerable<WeatherForecast> Get() { _log.Info("Hello, this is a Weather api!"); _log.Warn("Wran !!!"); _log.Error("Controller Error"); var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } } }
以上是“.NET Core下如何使用Log4Net記錄日志”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。