这篇文章主要介绍“ASP.NET Core如何使用Log4net实现日志记录功能”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“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实现日志记录功能”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注编程网行业资讯频道,小编每天都会为大家更新不同的知识点。