asp.net core中使用log4net

和之前的ASP.NET MVC中的使用LOG4NET的方法有些不同,这里先记录一下,使用步骤如下 :

  1. 建立 ASP.NET CORE项目中,NUGET中搜索log4net后下载安装

  2. 根目录建立 log4net.config文件,内容如下:










  
  
  
  
  
  
  
  
    
  




  
  
  
  


  1. Startup.cs文件中的Startup方法和ConfigureServices方法里的AddMvc代码改下,核心代码如下,记得引用相应的命名空间:

     //log4net日志
     public static ILoggerRepository repository { get; set; }
    
     public Startup(IConfiguration configuration)
     {
         Configuration = configuration;
    
         //加载log4net日志配置文件
         repository = LogManager.CreateRepository("NETCoreRepository");
         XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));
     }
    
     public IConfiguration Configuration { get; }
    
     // This method gets called by the runtime. Use this method to add services to the container.
     public void ConfigureServices(IServiceCollection services)
     {
    
         services.AddMvc(options =>
         {
             options.Filters.Add(); //加入全局异常类
         });
     }
    
  2. Models文件夹中建立 HttpGlobalExceptionFilter.cs 类,用于全局异常后记录到日志中,内容代码如下 :

using log4net;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication1.Models
{
///


/// 全局异常类
///

public class HttpGlobalExceptionFilter : IExceptionFilter
{
private ILog log = LogManager.GetLogger(Startup.repository.Name, typeof(HttpGlobalExceptionFilter));
public void OnException(ExceptionContext context)
{
log.Error(context.Exception);
}
}
}

  1. 下面是控制器的代码,有异常会自动记录下来,用那个log也能手工记录日志信息

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using log4net;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
private ILog log = LogManager.GetLogger(Startup.repository.Name, typeof(HttpGlobalExceptionFilter));
public IActionResult Index()
{
throw new Exception("牛腩自定义异常!!!"); //有异常则会记录到logfile文件夹中
return View();
}

    public IActionResult About()
    {
        ViewData["Message"] = "Your application description page.";
        log.Info("打开about页面了!!!"); //普通的记录日志
        return View();
    }

}

}

你可能感兴趣的:(asp.net core中使用log4net)