[C#] log4net separate log files programmatically

Preface
In C#, there is useful log framework. It is called "log4net". In this article, I would like to show how to separate log files. To start with, I will take an example. As you can see the image below, it is available to create 2 separated log files, "20200217_check.log" and "20200217_common.log".

 <Picture1> Separated log files "20200217_check.log" and "20200217_common.log"

The logged data in each log files are also separated like below.
<Picture2> Logged data in "20200217_check.log"

<Picture3> Logged data in "20200217_common.log"

To implement this, I used 2 different ILoggerRepository. The one is for "20200217_check.log" and the other is for "20200217_common.log". With these different ILoggerRepository, you can configure 2 different types of Logger. It means you can apply different format to each log files such as RollingAppender configuration, PatternLayout and so on.

Let's have several steps to do
Here are a few steps to implement separated each log files programmatically. 
1. Create New C# Project.
2. Add "log4net" library to your project.
3. Enter a few codes.
4. See results.


1. Create New C# Project.
   1) Choose [File] > [New] > [Project]

   2) Choose [Visual C#] > [Console(.Net Framework)] > Enter the name and work path > Press [OK]

2. Add "log4net" library to your project.
   1) Righ Click to [Reference] > [NuGet Package Manager]
 

   2) Search and Select "log4net" in the search box


   3) Click [Install] from the right window


3. Enter a few codes.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
using log4net.Config;
using log4net.Appender;
using log4net.Layout;
using log4net.Repository.Hierarchy;


namespace Log4NetTestMain01
{
    class Program
    {
        static void Main(string[] args)
        {
            new Program();
            Console.WriteLine("Press Any Key...");
            Console.ReadKey();
        }

        public Program()
        {
            Log Log = new Log();
            ILog CommonLogger = Log.GetLogger("common");
            CommonLogger.Fatal("COMMON LOGGER FATAL");
            CommonLogger.Error("COMMON LOGGER ERROR");
            CommonLogger.Warn("COMMON LOGGER WARN");
            CommonLogger.Info("COMMON LOGGER INFO");
            CommonLogger.Debug("COMMON LOGGER DEBUG");

            ILog CheckFileLogger = Log.GetLogger("check");
            CheckFileLogger.Fatal("CHECK FILE LOGGER FATAL");
            CheckFileLogger.Error("CHECK FILE LOGGER ERROR");
            CheckFileLogger.Warn("CHECK FILE LOGGER WARN");
            CheckFileLogger.Info("CHECK FILE LOGGER INFO");
            CheckFileLogger.Debug("CHECK FILE LOGGER DEBUG");

        }
    }

    class Log
    {
        /**
         * Field Area
         **/
        ILog Logger;       
        string FileName;
        PatternLayout Layout;
        string LogFileRootPath;
        RollingFileAppender RollingAppender;         

        /**
         * Default Constructor
         **/
        public Log()
        {

        }

        /**
         * set log config for common log.
         **/
        public ILog GetLogger(string LogKeyName)
        {           
           
            // create & Initialize fields
            Layout          = new PatternLayout();
            LogFileRootPath = "D:\\CCU\\logTest\\";
            RollingAppender = new RollingFileAppender();
            FileName        = "yyyyMMdd'_" + LogKeyName + ".log'";           
           
            // RollingAppender options
            RollingAppender.MaxSizeRollBackups  = 100;
            RollingAppender.AppendToFile        = true;
            RollingAppender.StaticLogFileName   = false;
            RollingAppender.MaximumFileSize     = "5MB";
            RollingAppender.Layout              = Layout;
            RollingAppender.Name                = LogKeyName;
            RollingAppender.File                = LogFileRootPath;
            RollingAppender.DatePattern         = FileName;
            RollingAppender.Encoding            = Encoding.UTF8;           
            RollingAppender.RollingStyle        = RollingFileAppender.RollingMode.Composite;
            RollingAppender.LockingModel        = new log4net.Appender.RollingFileAppender.MinimalLock();
            RollingAppender.ActivateOptions();

            // Layout options
            Layout = new log4net.Layout.PatternLayout("%d %-5p - %m%n");
            Layout.ActivateOptions();

            // LoggerRepository settings
            string repositoryName = string.Format("{0}Repository", LogKeyName);
            log4net.Repository.ILoggerRepository repository = LogManager.CreateRepository(repositoryName);
            string loggerName = string.Format("{0}Logger", LogKeyName);
            BasicConfigurator.Configure(repository, RollingAppender);
            Logger = LogManager.GetLogger(repositoryName, loggerName);

           
            return Logger;
        }

    }
}

4. See results.
To see the results, You have to click [Debug] > [Start without Debugging]. Shortly, you can see the prompt console window. It means the application finished successfully. All you have to do is just go to the output folder and open log files.

<Picture3> Output folder with 2 separated log files

<Picture4> Logged data in "20200217_check.log"

<Picture5> Logged data in "20200217_common.log"

Comments

Popular posts from this blog

$$ Regular Expression이 안먹는 경우

[Java] Install JDK and configure Environment variable

exception in thread main java.lang.unsupportedclassversionerror unsupported major.minor version 52.0