.NET: Easily Install Log4Net in .NET Web Application

Logging is an integral tool for debugging applications. For newer developers, or developers who don’t typically work in the .NET ecosystem, setting up Log4Net can be confusing and complicated.

First, we need to add Log4Net to our application with NuGet. Navigate to the top of Visual Studio and click:

 "Tools > NuGet Package Manager > Manage NuGet Packages for Solution" 

Next, in the search bar, type “Log4Net” and install the package to your project.

Open up your AssemblyInfo.cs file and add:

 [assembly: log4net.Config.XmlConfigurator(ConfigFile = "config.log4net", Watch = true)] 

Under your project’s directory, create a “config.log4net” file. This file is customizable but for today, we’re going to stick with a simple configuration that outputs to Visual Studio’s “Output” window and writes to a log file located in your project’s directory. Here’s the file content:

<?xml version="1.0" encoding="utf-8" ?>
    <!-- Need trace for web applications. -->
    <appender name="TraceAppender" type="log4net.Appender.TraceAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d [%t] %-5p %c %m%n"/>

    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="your-app-logs.txt" />
      <appendToFile value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />

      <level value="ALL"/>
      <appender-ref ref="TraceAppender"/>
      <appender-ref ref="FileAppender"/>

Now, add your logging code like so:

class ClassNeedsLogging {
        private static readonly ILog Logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public void MethodThatNeedsLogging() {
            Logger.Info("Hit MethodThatNeedsLogging");

That’s it. Now, you should see logging in the Visual Studio “Output” window. You’ll also be able to see logging in “{Your Project Directory}/your-app-logs.txt”.

Leave a Reply

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