Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Log4Net Integration in ASP.NET Core

Tech May 17 2

Method 1: Explicit Repository Configuration

Required NuGet packages: log4net and Microsoft.Extensions.Logging.Log4Net.AspNetCore

Initialize reposiotry during application startup:

public Startup(IConfiguration config, IWebHostEnvironment env)
{
    string appRoot = env.ContentRootPath;
    FileInfo configFile = new FileInfo(Path.Combine(appRoot, "Config", "log4net.xml"));
    
    ILoggerRepository repo = LogManager.CreateRepository("PrimaryRepo");
    XmlConfigurator.Configure(repo, configFile);
}

Usage example:

ILog logger = LogManager.GetLogger("PrimaryRepo", typeof(Startup));
logger.Info("Informational message");
logger.Warn("Warning notification");

Method 2: Default Repository via Builder

Configure through host builder:

public static IHostBuilder CreateHost(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder => 
        {
            webBuilder.UseStartup<Startup>();
        })
        .ConfigureLogging(logConfig =>
        {
            logConfig.AddFilter("System", LogLevel.Warning);
            logConfig.AddFilter("Microsoft", LogLevel.Warning);
            logConfig.AddLog4Net("Config/log4net.xml");
        });

Basic usage:

ILog log = LogManager.GetLogger(typeof(Program));
log.Debug("Debug trace");
log.Error("Exception occurred");

Alternative using factory:

ILoggerFactory loggerFactory = ... // Injected dependency
loggerFactory.CreateLogger<T>().LogError("Error message");
loggerFactory.CreateLogger<T>().LogWarning("Warning notice");

Controller implementation:

using Microsoft.Extensions.Logging;

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;

    public HomeController(ILogger<HomeController> logger)
    {
        _logger = logger;
    }
    
    public IActionResult Index()
    {
        _logger.LogError("Controller error");
        return View();
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.