Skip to content

ConsoleApp (.NET Framework)

Catalin Gavan edited this page Nov 27, 2021 · 9 revisions

These steps describe how to install and configure KissLog for a .NET Framework Console application.

A full working example can be found here.

By following the install instructions, you will:

  • create a "main" logger instance and use it throughout the Main(string[] args) method execution
  • register LocalTextFileListener listener which will save the captured data to logs folder

Instructions

  1. Install NuGet Package
PM> Install-Package KissLog
  1. Update Program.cs
using KissLog;
using KissLog.Listeners.FileListener;
using System;

namespace ConsoleApp_NetFramework
{
    class Program
    {
        static void Main(string[] args)
        {
            // create a "main" logger and update Logger.Factory.Get() to always return this instance
            Logger.SetFactory(new LoggerFactory(new Logger(url: "ConsoleApp/Main")));

            ConfigureKissLog();

            var logger = Logger.Factory.Get();

            logger.Trace("Hey there!");

            try
            {
                string value = null;
                Console.Write($"value.length = {value.Length}");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                logger.Error(ex);
            }
            finally
            {
                // notify the listeners
                Logger.NotifyListeners(logger);
            }
        }

        private static void ConfigureKissLog()
        {
            KissLogConfiguration.Listeners
                .Add(new LocalTextFileListener("logs", FlushTrigger.OnFlush));
        }
    }
}

Write logs

Use Logger.Factory.Get() to receive the "main" logger instance created at the beginning of the Main() method.

We call Logger.NotifyListeners which will execute OnFlush() method for the registered listeners.

namespace ConsoleApp_NetFramework
{
    class Program
    {
        static void Main(string[] args)
        {
            Logger.SetFactory(new KissLog.LoggerFactory(new Logger(url: "ConsoleApp/Main")));

            // [...]

            var logger = Logger.Factory.Get();
            
            logger.Trace("Hey there!");
            
            Logger.NotifyListeners(logger);
        }
    }
}