ASP.NET Core 使用日志组件

本文主要介绍在ASP.NET Core中使用两种日志组件

  • Logging:Flexible & free open-source logging for .NET
  • Log4Net: Apache log4net框架在Microsoft .NET平台的实现

一 使用ASP.NET Core本身自带了轻量级的日志记录日志框架Logging

appsettings.json中对Logging的配置:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

Logging的使用

    public class HomeController : Controller
    {
       
        private readonly ILogger _logger;
        public HomeController(ILogger logger)
        {
            _logger = logger;
        }
        public IActionResult Index()
        {
            _logger.LogError("logger记录错误");
            return View();
        }
    }

错误将打印在控制台


image.png

二使用第三方日志组件(再此使用Log4Net)

ASP.NET Core 2.0已经可以使用Log4Net,安装Nuget包,我安装的是log4net 2.08

log4net.config


  
  
    
      
      
      
      
      
      
      
      
      
      
      
        
        
        
      
    
    
      
      
    
  

修改启动类
        public static ILoggerRepository Repository;//log4net
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            Repository = LogManager.CreateRepository("NETCoreRepository");
            XmlConfigurator.Configure(Repository, new FileInfo("log4net.config"));
        }
在控制器中调用Log4Net
       private ILog log = LogManager.GetLogger(Startup.Repository.Name, typeof(HomeController));
        private readonly ILogger _logger;
        public HomeController(ILogger logger)
        {
            _logger = logger;
        }
        public IActionResult Index()
        {
            _logger.LogError("logger记录错误");
            log.Error("log4net记录错误");
            return View();
        }
结果:
image.png
image.png

你可能感兴趣的:(ASP.NET Core 使用日志组件)