.NETCore下如何使用Log4Net记录日志-创新互联
小编给大家分享一下.NET Core下如何使用Log4Net记录日志,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
成都创新互联公司主要从事成都网站设计、网站制作、网页设计、企业做网站、公司建网站等业务。立足成都服务青云谱,十载网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:13518219792Log4Net
相信大家都很熟悉了,算是比较主流和著名的日志组件了。
官网: logging.apache.org
开源地址: https://github.com/apache/logging-log4net
很好实践
在项目中添加组件包
Install-Package log4net
添加log4net.config
文件
控制台项目
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(); }).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 IEnumerableGet() { _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记录日志”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!
网站栏目:.NETCore下如何使用Log4Net记录日志-创新互联
URL标题:http://ybzwz.com/article/coojop.html