Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use Log4net to implement logging function in ASP.NET Core

Shulou Source: shulou.com Published: 2022-06-01 06:38:44 09月14日 Update

This article mainly introduces "ASP.NET Core how to use Log4net to achieve logging function" related knowledge, editor through the actual case to show you the operation process, the operation method is simple and fast, practical, I hope that this "ASP.NET Core how to use Log4net to achieve logging function" article can help you solve the problem.

First, install Log4net1 and use Nuget package for installation

Right-click the dependency and select manage NuGet packages, as shown in the following figure:

Enter log4net in the browsing interface, and then click install, as shown in the following figure:

2. Use the package Manager console to install

Use the Install-Package Log4net command to install, as shown in the following figure:

Configure the configuration files used by log4net

The configuration file is as follows:

/ / specify the directory where the log file is saved. 3. Configure the Startup.cs class to use log4netpublic static ILoggerRepository repository {get; set;} public Startup (IConfiguration configuration) {Configuration = configuration; repository = LogManager.CreateRepository ("NETCoreRepository") / / specify the configuration file XmlConfigurator.Configure (repository, new FileInfo ("log4net.config"))} IV. Inject log4netusing 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 into the controller Public HomeController (IHostingEnvironment hostingEnv) {this.log = LogManager.GetLogger (Startup.repository.Name, typeof (HomeController));} public IActionResult Index () {log.Error ("test log"); 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});}}

Test results:

This is the end of the introduction to "how ASP.NET Core uses Log4net to achieve logging". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Tags: Log configuration file function knowledge program industry control test management different practical content command practical console controller article method Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Redmi Docker NVidia Xiaomi