April 15, 2021

How to maintain new Log Files for every execution using Log4net for .NET Application?

Overview:

We recently implemented a Console Application for a Construction Engineering Company based out of Washington, United States using C# for automated execution with the help of Windows Tasks Scheduler to read the data from SharePoint List and create files in the local file system as per the requirements from the client. Most of us have used “Log4net” as a logging tool for our .NET Application. We came across some different requirements wherein we need to maintain the log for each execution in a separate log file. With OOTB configuration the logs are appended in a single file. So, how can we customize this thing?

To achieve this, we will add one custom function of log configuration in our program file. We will append the current date and time after the file name. Using the current date and time we could create a new file with a unique name on every execution. Using this method will create a new file on every execution. So, now let’s get started!

Step 1: Add NuGet Package for "Log4net"

Let’s start with creating an application in Visual Studio. After that, we will use the “Log4net” NuGet package. We will add the “Log4net” library from the Manage NuGet Package. Follow the below steps to add “Log4net”.
  1. In the "Solution Explorer Window," select and right-click on your project
  2. Click "Manage NuGet Packages..."
  3. Click "Online" and then type log4net in the search box
  4. Select the log4net package you would like to install
  5. Click "Install" to start the installation process

Step 2: Add custom method for configuration 

We will create a new method in our class (.cs) file. You can use any class(.cs) file to create this method. Here, we will use the same class (.cs) file available in our solution!

Add the below lines of code.
     public static void initLog4Net()  
     {  
       try  
       {  
         var hierarchy = (log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.GetRepository();  
         hierarchy.Configured = true;  
         var rollingAppender = new log4net.Appender.RollingFileAppender  
         {  
           File = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + "\\" +  
           "LogFiles\\" + "C#LogFile_" + DateTime.Now.ToString("yyyyMMddTHHmm") + ".log",  
           AppendToFile = true,  
           LockingModel = new log4net.Appender.FileAppender.MinimalLock(),  
           Layout = new log4net.Layout.PatternLayout("%date [%thread] %level %logger - %message%newline")  
         };  
         var traceAppender = new log4net.Appender.TraceAppender()  
         {  
           Layout = new log4net.Layout.PatternLayout("%date [%thread] %level %logger - %message%newline")  
         };  
         hierarchy.Root.AddAppender(rollingAppender);  
         hierarchy.Root.AddAppender(traceAppender);  
         rollingAppender.ActivateOptions();  
         hierarchy.Root.Level = log4net.Core.Level.All;  
       }  
       catch (global::System.Exception ex)  
       {  
         new Exception(ex.Message);  
       }  
     }  
Using the above code, we can create a new log file on every execution in the same folder from where we execute this application.

As shown in the below code snippet we declare our filename with appended date-time format.

 File = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + "\\" +  
           "LogFiles\\" + "CDMDepartment_" + DateTime.Now.ToString("yyyyMMddTHHmm") + ".log",  
This will generate the new file in the “LogFiles” folder. The name of the log will start with “C#LogFile_” and with that, it will add the current date-time in (“yyyyMMddTHHmm”) format. We can change the name of the file as well as the date-time format.

Here we will make sure we would add the proper format of date and time based on how many times we execute this application in one day.

Step 3: Create an instance of the logger file

To create an instance of logger file add the below code within a class.
 public static class Program  
   {  
     private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);  
   }  

Step 4: Call the log file and use it

We need to call the method for creating a log. We need to call this method at the starting of the application so we can use it in our code.
 static void Main()  
     {  
         Console.Clear();  
         initLog4Net();  
         log.Info("Welcome to Application Program");  
     }  
As shown above, after a call of the “initLog4Net” function we used the “log.Info” to print this to the logger file.

We can also use other formats of the logging as following.
  • Log.Error();
  • Log.Debug();
  • log.Warn();
  • log.Fatal();

Now we can run our application and it will create a file as “C#LogFile_20201221T2238”.




Conclusion: 

This is how we can use the “Log4Net” library and we can create new a file on every execution of an application. Hope, this helps.

If you have any questions you can reach out our SharePoint Consulting team here.

1 comment:

  1. I had tried to use app.config in various ways but it never worked. I used your code and also changed one setting staticfilename to true and it worked

    ReplyDelete