Standalone configuration file

Extract log4net settings into a standalone log4net.config file, separate from web.config; load the configuration automatically via assembly attributes.

1 Create log4net.config

Place it in the website root directory

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>

  <log4net>
    <!--Save logs to txt file-->
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <!--Log root path: website root/logs-->
      <param name="File" value="logs\\" />
      <!--Append content to file-->
      <param name="AppendToFile" value="true" />
      <!--Keep maximum 10 backup log files-->
      <param name="MaxSizeRollBackups" value="10" />
      <!--Dynamic filename generated by date-->
      <param name="StaticLogFileName" value="false" />
      <!--Folder structure logs/yyyy/MM/yyyy-MM-dd.log -->
      <param name="DatePattern" value="yyyy\\MM\\yyyy-MM-dd&quot;.log&quot;" />
      <!--Roll log files by date-->
      <param name="RollingStyle" value="Date" />

      <!--Log output format-->
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d [%t] %-5p %c - %m%n" />
      </layout>
    </appender>

    <!--Root logger binding appender-->
    <root>
      <level value="ALL" />
      <appender-ref ref="RollingLogFileAppender" />
    </root>
  </log4net>
</configuration>Code language: HTML, XML (xml)

2 Initialize in AssemblyInfo.cs

Open Properties/AssemblyInfo.cs within your project, append the following code at file end:

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]Code language: JSON / JSON with Comments (json)
  • ConfigFile="log4net.config":Specify path for standalone config file (website root folder)
  • Watch=true:Enable hot‑reload. Changes to log4net.config take effect without website restart

3 Invoke code on page

using log4net;

public partial class Default : System.Web.UI.Page
{
    // Create logger instance
    public ILog log = LogManager.GetLogger("Logger for Default.aspx page");

    protected void Page_Load(object sender, EventArgs e)
    {
        log.Info("Normal log");
        log.Error("Error log");
        log.Debug("Debug message");
    }
}

Standalone configuration file

Leave a Reply

Your email address will not be published. Required fields are marked *