Blog for Junior Developers C#/.NET

Wednesday, May 08, 2024

In a previous blog post, I touched on exception handling in C#. I've introduced you to some popular methods of throwing exceptions that are often used by programmers. Then I also mentioned that if we want to handle an exception well, we should necessarily save detailed information about it, for example to a file. We should not allow situations where this error is not recorded in the catch. What's the best way to do this? .NET developers have plenty of libraries to choose from that allow them to save such logs to files. Should we use one of these libraries? If so, which one? How to save such logs? Or maybe we should write our own logger that will save such information to a file? You will find the answers to all these questions in this article.

logging-data-to-a-file-in-csharp-using-the-nlog-library.jpg

Your own logger?


First of all, in my opinion, you should not write a new, own logger, your own library that will save such logs. Why? There are several reasons. First of all, writing your own logger will require a lot of work from you, so you will have to spend a lot of time on it, which you could otherwise spend writing your own application. Secondly, since there are already some solutions available, free libraries, a lot of other programmers certainly use them, and therefore they are well tested by them, so they probably already work well. If you write your own library, over time there will certainly be some errors that you will have to correct, and it will probably not be reliable right away. So, it seems to me that, at least from a business point of view, there is no point in writing such a library for your own use from scratch, it is better to use a ready-made solution. However, if you want to write such a library, not for business purposes, but to improve your skills, then it may be a good idea. Writing such a library will definitely help you with this.


Which logging library should I choose?


So, which data logging library should you choose? There are quite a few good free libraries you can use in your application. These include: NLog, log4net, serilog, and elmah. In my opinion, each of them is good, but I use NLog most often, although the others are also good. The examples below will be written using the NLog library.


NLog installation and configuration


NLog has quite well-written documentation, so I recommend you read it first. You will also find some usage examples there. To add the NLog library to a project written in C#, install the following packages using NuGet: NLog, NLog.Schema and NLog.Config. After installation, the NLog.config and NLog.xsd files should be added to the project. Before you start saving data, you should complete the configurations in the NLog.config file. There are a lot of comments there describing how to do it correctly, you can try this configuration to start with:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
  
 <targets>
    <target 
      xsi:type="File" 
      name="error" 
      fileName="${basedir}/logs/error/${shortdate}.log"
      layout="${longdate} ${uppercase:${level}} ${message}" />
    
    <target 
      xsi:type="File"             
      name="info" 
      fileName="${basedir}/logs/info/${shortdate}.log"            
      layout="${longdate} ${uppercase:${level}} ${message}" />
  </targets>
  
  <rules>
    <logger 
      name="*" 
      minlevel="Error" 
      writeTo="error" />
        
    <logger 
      name="*" 
      minlevel="Info"
      maxlevel="Warn" 
      writeTo="info" />
  </rules>
  
</nlog>


Thanks to this configuration, a logs folder will be created in the application folder, with two more folders in it, i.e. error, where application errors will be saved, and info, where information logs and warnings will be saved. All logs will be saved to text files. The name will contain the current date and the log extension. You can easily separate logs depending on their type.


How to save logs in the application:


Below is the code used in the .NET framework console application:

namespace App
{
    class Program
    {
        private static NLog.Logger _logger = 
            NLog.LogManager.GetCurrentClassLogger();
        static void Main(string[] args)
        {
            _logger.Info("Application started...");

            try
            {
                //...
            }
            catch (Exception ex)
            {
                _logger.Error(ex);
                throw;
            }
            finally
            {
                _logger.Info("Application stopped...");
            }
        }
    }
}


First, we initialize the static private field _logger, of the Logger class, of course from the NLog library. When calling the Main method, we first write information that the application has started, and in the finally block we add to the log file that the application has finished. These 2 logs will be placed in the info folder and will look like this:

2020-09-15 17:19:17.6081 INFO Application started...
2020-09-15 17:19:17.6381 INFO Application stopped...


 In turn, if an exception occurs in the try block, the error log will be saved in the appropriate file, in the error folder. An example of such a logo:

2020-09-15 17:19:39.1021 ERROR System.Exception: exception
   at MyApp.Program.Main(String[] args) in C:\App\Program.cs:line 19


SUMMARY:


As you can see, there is no need to create your own logger. Nowadays, we have a lot of free libraries to choose from that we can use in C#. They only require you to spend a few minutes preparing the appropriate configuration, and then you can easily log various information to a file. This way, if there is an error in your application, you will be able to diagnose it easily. Let me know if you use NLog in your projects, or maybe some other library has worked for you? Please share your experiences :)

Author of the article:
Kazimierz Szpin

KAZIMIERZ SZPIN
Software Developer C#/.NET, Freelancer. Specializes in ASP.NET Core, ASP.NET MVC, ASP.NET Web API, Blazor, WPF and Windows Forms.
Author of the blog CodeWithKazik.com

Previous article - Simple Rules to Remember When Handling Exceptions in C#
Next article - Extension Methods in C#, or How to Easily Extend an Existing Type
Dodaj komentarz

Search engine

© Copyright 2024 CodeWithKazik.com. All rights reserved. Privacy policy.
Design by Code With Kazik