这篇文章主要介绍“ASP.NET Core如何使用Log4net实现日志记录功能”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“ASP.NET Core如何使用Log4net实现日志记录功能”文章能帮助大家解决问题。
在依赖项上面右键,选择“管理NuGet程序包”,如下图所示:
在浏览界面输入log4net,然后点击安装,如下图所示:
使用Install-Package 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>
public static ILoggerRepository repository { get; set; } public Startup(IConfiguration configuration) { Configuration = configuration; repository = LogManager.CreateRepository("NETCoreRepository"); // 指定配置文件 XmlConfigurator.Configure(repository, new FileInfo("log4net.config")); }
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实现日志记录功能”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。