ASP.NET Core使用Log4net實現日志記錄功能

一、安裝Log4net

1、使用Nuget包進行安裝

在依賴項上面右鍵,選擇“管理NuGet程序包”,如下圖所示:

在瀏覽界面輸入log4net,然後點擊安裝,如下圖所示:

2、使用程序包管理器控制臺進行安裝

使用Install-Package Log4net命令進行安裝,如下圖所示:

二、配置log4net使用的配置文件

配置文件如下:

<?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="D:\study\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>

三、在Startup.cs類裡面配置使用log4net

public static ILoggerRepository repository { get; set; }
public Startup(IConfiguration configuration)
{
            Configuration = configuration;
            repository = LogManager.CreateRepository("NETCoreRepository");
            // 指定配置文件
            XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));
}

四、在控制器裡面註入log4net

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

namespace NetCoreLogDemo.Controllers
{
    public class HomeController : Controller
    {
        private ILog log;

        public HomeController(IHostingEnvironment hostingEnv)
        {
            this.log = LogManager.GetLogger(Startup.repository.Name, typeof(HomeController));
        }

        public IActionResult Index()
        {
            log.Error("測試日志");
            return View();
        }

        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";

            return View();
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            return View();
        }

        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

測試結果:

到此這篇關於ASP.NET Core使用Log4net實現日志記錄功能的文章就介紹到這瞭。希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: