Logging is a crucial aspect of software development, helping you track issues, monitor behavior, and maintain applications more effectively. log4net is a powerful, flexible logging library for .NET applications, inspired by the Java-based log4j. This guide shows how to integrate log4net into a C# project with a working example.
Key Features of log4net
- Easy to configure via XML or code.
- Supports multiple logging targets (file, console, event log, etc.).
- Thread-safe logging.
- Fine-grained control over log levels:
DEBUG,INFO,WARN,ERROR,FATAL.
Step-by-Step Guide:
1. Install log4net via NuGet
Open the NuGet Package Manager Console and run:
Install-Package log4net
2. Add Configuration in App.config or Web.config
Add the following inside your configuration file:
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="Logs\\app.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="1MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingFileAppender" />
</root>
</log4net>
</configuration>
Note: Ensure the
Logs folder exists or your application has permission to create/write to it.
3. Initialize and Use log4net in C# Code
Here’s a simple example in Program.cs:
using System;
using log4net;
using log4net.Config;
using System.Reflection;
class Program
{
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
static void Main(string[] args)
{
XmlConfigurator.Configure(); // Loads config from App.config
log.Info("Application started");
try
{
int a = 10, b = 0;
int result = a / b;
}
catch (Exception ex)
{
log.Error("An error occurred", ex);
}
log.Warn("This is a warning");
log.Debug("Debug message");
log.Fatal("Fatal error simulation");
Console.WriteLine("Done. Check the Logs folder.");
}
}
Output Example
This configuration writes logs to Logs\app.log with entries like:
2025-05-28 10:35:14,553 [1] INFO Program - Application started 2025-05-28 10:35:14,559 [1] ERROR Program - An error occurred System.DivideByZeroException: Attempted to divide by zero. at Program.Main(String[] args)
No comments:
Post a Comment