Skip to content

ConsoleApp (.NET Core)

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

These steps describe how to install and configure KissLog for a .NET Core 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 KissLog as Microsoft.Extensions.Logging.ILogger<> adapter
  • register LocalTextFileListener listener which will save the captured data to logs folder

Instructions

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

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

            ConfigureKissLog();

            IConfiguration configuration = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .Build();

            var serviceCollection = new ServiceCollection();
            ConfigureServices(serviceCollection, configuration);
            var serviceProvider = serviceCollection.BuildServiceProvider();

            ILogger logger = serviceProvider.GetService<ILogger<Program>>();
            
            logger.LogTrace("Hey there!");

            try
            {
                string value = null;
                Console.Write($"value.length = {value.Length}");
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex);
                logger.LogError(ex, "Unexpected exception");
            }
            finally
            {
                // notify the listeners
                var loggers = Logger.Factory.GetAll();
                Logger.NotifyListeners(loggers);
            }
        }

        private static void ConfigureServices(IServiceCollection services, IConfiguration configuration)
        {
            services.AddLogging(logging =>
            {
                logging
                    .AddConfiguration(configuration.GetSection("Logging"))
                    .AddKissLog(options =>
                    {
                        options.Formatter = (FormatterArgs args) =>
                        {
                            if (args.Exception == null)
                                return args.DefaultValue;

                            string exceptionStr = new ExceptionFormatter().Format(args.Exception, args.Logger);

                            return string.Join(Environment.NewLine, new[] { args.DefaultValue, exceptionStr });
                        };
                    });
            });
        }

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

Write logs

Logs can be written using Microsoft.Extensions.Logging.ILogger<> interface.

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

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

            // [...]

            ILogger logger = serviceProvider.GetService<ILogger<Program>>();
            
            logger.LogTrace("Hey there!");
            
            var loggers = Logger.Factory.GetAll();
            Logger.NotifyListeners(loggers);
        }
    }
}