Introduction
- Definition
Log4net = Log for .NET, it is the official .NET‑platform port of Apache Log4j (classic Java logging framework), a mature open‑source logging library. - Core Functions
After referencing it in your project, you can quickly implement application logging without writing file‑read‑write logic from scratch. It records runtime information and exception stack traces to assist debugging and troubleshooting production‑environment issues. - Terminology Reference
- Log4j: Well‑established logging component for Java ecosystem
- Log4net: Log4j port adapted for C#/.NET
Installation
For modern .NET projects, NuGet installation is recommended:
dotnet add package log4net
You may also search for log4net inside Visual Studio’s Manage NuGet Packages UI and install it in one click.
Early log4net versions required manual DLL download and reference; NuGet is the mainstream approach today.
Log4Net Environment Setup
log4net works with all project types: console apps, desktop applications and web applications alike.
Workflow
Step 1: Modify Web.config and add log4net configuration
<?xml version="1.0"?>
<configuration>
<configSections>
<!-- Register log4net configuration section -->
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
</configSections>
<log4net>
<!-- Date‑rolling file appender -->
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<!-- Log storage path. Use relative paths; avoid hard‑coded USB‑drive absolute paths -->
<param name="File" value="logs\\"/>
<!-- Append mode: true = keep appending logs; false = clear file on each startup -->
<param name="AppendToFile" value="true"/>
<!-- Maximum number of log files to retain -->
<param name="MaxSizeRollBackups" value="10"/>
<!-- Fixed filename toggle: false = generate separate files by date -->
<param name="StaticLogFileName" value="false"/>
<!-- File naming pattern -->
<param name="DatePattern" value="yyyy-MM-dd".log""/>
<!-- Rolling strategy: Date = split logs by calendar date -->
<param name="RollingStyle" value="Date"/>
<!-- Log output format template -->
<layout type="log4net.Layout.PatternLayout">
<param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
<!-- ❗Original screenshot template contained redundant %loggername causing trailing garbage text; cleaned up -->
</layout>
</appender>
<!-- Root logger configuration, global scope -->
<root>
<!-- Log level all: output every severity; valid values: DEBUG/INFO/WARN/ERROR/FATAL/OFF -->
<level value="all"/>
<!-- Bind the appender defined above -->
<appender-ref ref="RollingLogFileAppender"/>
</root>
</log4net>
</configuration>Code language: HTML, XML (xml)
- Do not hard‑code absolute paths like
G:\xxx. They break after server deployment; use relative pathlogs\\instead; - In production environment, set
leveltoINFOorERRORto prevent disk bloat from excessive DEBUG logs.
Step 2: Global Log4Net initialization
Add initialization code inside Application_Start in your project’s Global.asax, loads configuration on application startup
protected void Application_Start(object sender, EventArgs e)
{
// Initialize log4net, read configuration from Web.config
log4net.Config.XmlConfigurator.Configure();
}Code language: JavaScript (javascript)
Note: If you omit this line, logging calls will produce zero log files. This is a very common pitfall.
Step 3: Acquire Logger instance and emit logs in your page
Write calling code in Default.aspx.cs. Logging may be invoked anywhere; this sample demonstrates one page only.
using log4net;
public partial class _Default : System.Web.UI.Page
{
// Obtain logger instance; string parameter is logger name, freely configurable
public static readonly ILog log = LogManager.GetLogger("logger-name");
protected void Page_Load(object sender, EventArgs e)
{
log.Info("Normal log");
log.Error("Error log");
// Additional available levels
// log.Debug("Debug log");
// log.Warn("Warning log");
// log.Fatal("Fatal error log");
}
}
Best‑practice guideline: declare ILog as static readonly to avoid repeated instance creation and improve performance.
Runtime Behaviour Overview
- After application startup, a
logsfolder will be auto‑created under website root; - Log files such as
2026-08-04.logare generated automatically; - Sample output inside log file:
2026-08-04 15:30:22,123 [6] INFO logger-name - Normal log
2026-08-04 15:30:22,129 [6] ERROR logger-name - Error logCode language: CSS (css)
Additional Notes
- Besides file output, Log4Net supports console, database and email appenders;
- For new projects, consider comparing
NLog/Serilog, which offer better .NET Core/.NET 5+ support. Log4net is mostly used for maintaining legacy WebForm and WinForms projects.
Introduction and Installation