hackajob Insider

How to Log in ASP.NET Core Web Apps using log4net

Written by hackajob Staff | Nov 21, 2021 12:00:00 AM

We can all agree - it can be frustrating when your code works so smoothly in a local environment but doesn't work as expected once deployed to production. Logging can be a great way to see how your apps behave in different environments. When something goes wrong, you can check from the log instead of spending hours guessing what might have caused the error. Its simple, right?

In this quick ASP.NET Core tutorial, we'll cover how to implement logging in a Web app using log4net. Let's start by talking about what log4net is (if you just want to get straight to tutorial business, scroll down a little more).

What is log4net?

log4net is one of the most common logging frameworks for .NET applications. It's an oldie but goodie, used by many developers for over 20 years. This framework is like the grandparent of all modern .NET logging frameworks.

There are of course newer logging frameworks such as NLog and Serilog as well. The NLog is mostly known for its clean code base configuration, and Serilog is mainly known for its support for structured logging.

The Popular Trio. Figure 1. The most popular logging frameworks in .NET

The log4net supports a bunch of logging targets, which are also called appenders. This framework is so huge and has a large developer community that you can always find a custom implementation on the internet when there is an appender it doesn't support. It also offers structured logging, though not as straightforward as in Serilog.

So certainly, log4net still has plenty to offer in today's fast-paced world!

The log4net appenders (logging targets)

With log4net, you can output logs to different destinations. This framework supports many appenders, but here are four common ones:

  • Console appender — writes log messages to a console window.
  • File appender — writes log messages to a simple text file.
  • Rolling-file appender — similar to the file appender but offers more options such as storing logs of different days in different files.
  • ADO.NET appender — which you can use to store the logs in a database.

Logging levels in log4net

Everything doesn't need to get logged—it can be overwhelming, and you could end up with a lot of unnecessary information! For that reason, log4net has the following log levels, which are defined in order of increasing priority:

  • ALL (everything gets logged)
  • DEBUG
  • INFO
  • WARN
  • ERROR
  • FATAL
  • OFF (nothing gets logged)

It's important to note that once you set a log level, the lower priority levels will be ignored. For example, if you set the log level to ERROR, then all warning, info, and debug messages will not be logged.

How to setup log4net in an ASP.NET Core Web App

Now for the good stuff. Let's add log4net in an ASP.NET Core Web App project and save the logs in a rolling file. For this example, we'll set up a config to generate a new log file every 1 minute. In actual implementations, you can actually generate a new file every hour or day, or even based on the maximum file size.

We use .NET 5.0 as the target framework and Visual Studio as the code editor. Here's the structure of the project:

Figure 2. The structure of an ASP.NET Core Web App project

Step 1: Install log4net

To install log4net, one of the options is via the Package Manager. If you're using Visual Studio, go to Tools > NuGet Package Manager > Package Manager Console, then type the following command:

PM> Install-Package Microsoft.Extensions.Logging.Log4Net.AspNetCore

This will install both the logging extensions of log4net in ASP.NET Core and the log4net library itself.

Step 2: Add the log4net.config file

In your project, add a new file and name it log4net.config. After that, copy-paste the following code into the file:

<log4net>
  <root>
    <level value="WARN" />
    <appender-ref ref="RollingFile" />
  </root>
  <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
    <appendToFile value="true" />
    <file value="D:\Projects\LoggingDemo\logs\logfile" />
    <rollingStyle value="Date" />
    <datePattern value="yyyyMMdd-HHmm" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date %-5level %logger.%method [%line] - MESSAGE: %message%newline" />
    </layout>
  </appender>
</log4net>

The above config saves the logs in the "D:\Projects\LoggingDemo\logs" folder and rolls the log file every minute. You can change the rolling period by adjusting the datePattern value. For example, a date pattern of "yyyyMMdd" will roll every day. See System.Globalization.DateTimeFormatInfo for a list of available patterns.

Also, notice that in this case, we use the "WARN" log level. This means that all the info and debug messages will be ignored.

Step 3: Modify the Program.cs file

Double-click the Program.cs file to open it. Then, add the following code (see line 20-22) to use log4net as the default logging framework:

.ConfigureLogging(builder => {
builder.AddLog4Net("log4net.config");
})

Figure 3. Using log4net as the default logging

Step 4: Test if the log files created

Add the following lines in the IndexModel() of the Index.cshtml.cs page:

_logger.LogDebug("Hey, this is a DEBUG message.");
_logger.LogInformation("Hey, this is an INFO message.");
_logger.LogWarning("Hey, this is a WARNING message.");
_logger.LogError("Hey, this is an ERROR message.");

Figure 4. Changing the Index.cshtml.cs file for testing

Run the code and wait until the web app is ready. Check the log folder, and you should see a new log file created. When you open the file, it shows the following content:

Figure 5. The logfile

Notice that only warning and error messages were there. This is because in the log4net.config file, we specified "WARN" as the log level.

Wait for around 1 minute and click the Home menu in the Web app:

Figure 6. Clicking the Home menu to trigger logging

If you want, repeat the above process every one minute, and you'll see how each new log file is created in the log folder. Here's an example output:

Figure 7. A log file is created every one minute

Conclusion

Now, you've learned how to implement logging using log4net in an ASP.NET Core Web Application. Try this in your project if you don't have any logging implementation yet. You may want to experiment with different types of appenders.

Understanding how this framework works may also come in handy when you're working on legacy codebases in the future (who knows? 🙂). We hope you had a good time reading this article—and happy coding!

Like what you've read or want more like this? Let us know! Email us here or DM us: Twitter, LinkedIn, Facebook, we'd love to hear from you.