为了账号安全,请及时绑定邮箱和手机立即绑定

Asp.net core中使用log4net

标签:
C#

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

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

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

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<!-- This section contains the log4net configuration settings -->
<log4net>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout" value="%date [%thread] %-5level %logger - %message%newline" />
</appender>

<!--<appender name="FileAppender" type="log4net.Appender.FileAppender">
  <file value="log-file.log" />
  <appendToFile value="true" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  </layout>
</appender>-->

<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
  <file value="logfile/" />
  <appendToFile value="true" />
  <rollingStyle value="Composite" />
  <staticLogFileName value="false" />
  <datePattern value="yyyyMMdd'.log'" />
  <maxSizeRollBackups value="10" />
  <maximumFileSize value="1MB" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
  </layout>
</appender>

<!-- Setup the root category, add the appenders and set the default level -->
<root>
  <level value="ALL" />
  <appender-ref ref="ConsoleAppender" />
  <appender-ref ref="FileAppender" />
  <appender-ref ref="RollingLogFileAppender" />
</root>

</log4net>
</configuration>

  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<Models.HttpGlobalExceptionFilter>(); //加入全局异常类
        });
    }
  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
{
/// <summary>
/// 全局异常类
/// </summary>
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();
    }

}

}

点击查看更多内容
1人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消