2020年9月24日星期四

.NET Core 下使用 Log4Net 记录日志

Log4Net相信大家都很熟悉了,算是比较主流和著名的日志组件了。

  • 官网 id="最佳实践">最佳实践

    在项目中添加组件包

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

    AspNetCore项目

    新建一个静态类,写一个扩展方法UseLog4Net(),用于log4net初始化。

    public static class Log4NetExtensions{ public static IHostBuilder UseLog4Net(this IHostBuilder hostBuilder) {  var log4netRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());  

    扩展方法返回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();  } }}

    原文转载:http://www.shaoqun.com/a/477590.html

    首信易支付:https://www.ikjzd.com/w/1841

    inkfrog:https://www.ikjzd.com/w/668

    costco:https://www.ikjzd.com/w/1680


    Log4Net相信大家都很熟悉了,算是比较主流和著名的日志组件了。官网id="最佳实践">最佳实践在项目中添加组件包Install-Packagelog4net添加log4net.config文件<?控制台项目usinglog4net;usinglog4net.Config;usingSystem;usingSystem.IO;usingSystem.Reflect
    adore:https://www.ikjzd.com/w/2202
    isbn:https://www.ikjzd.com/w/174
    2019卖家如何在亚马逊上销售自有品牌产品?:https://www.ikjzd.com/home/17667
    亚马逊账户被关,怎样的申诉才最有效?:https://www.ikjzd.com/home/99883
    Keyword Tool Dominator:https://www.ikjzd.com/w/208

没有评论:

发表评论