Skip to content

dotnet ConsoleApp

Catalin Gavan edited this page Oct 15, 2024 · 1 revision

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

Working example and other use cases can be found on the KissLog ConsoleApp integrations page.

Instructions

  1. Install NuGet Package
PM> Install-Package KissLog.AspNetCore
  1. Update Program.cs
using KissLog;
using KissLog.AspNetCore;
using KissLog.CloudListeners.Auth;
using KissLog.CloudListeners.RequestLogsListener;
using KissLog.Formatters;
 
IConfiguration configuration = new ConfigurationBuilder()
    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
    .Build();
 
ConfigureKissLog(configuration);
 
var services = new ServiceCollection();
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 });
            };
        });
});
var serviceProvider = services.BuildServiceProvider();
 
// set a global "Logger" that will be reused throughout the application execution
Logger.SetFactory(new KissLog.LoggerFactory(new Logger(url: "ConsoleApp/Main")));
 
ILogger logger = serviceProvider.GetRequiredService<ILogger<Program>>();
 
logger.LogInformation("Hello World!");
 
var loggers = Logger.Factory.GetAll();
Logger.NotifyListeners(loggers);
 
void ConfigureKissLog(IConfiguration configuration)
{
    KissLogConfiguration.Listeners
        .Add(new RequestLogsApiListener(new Application("_OrganizationId_", "_ApplicationId_"))
        {
            ApiUrl = "https://api.logbee.net/",
            UseAsync = false
        });
}

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.

// [...]

Logger.SetFactory(new KissLog.LoggerFactory(new Logger(url: "ConsoleApp/Main")));

ILogger logger = serviceProvider.GetService<ILogger<Program>>();

logger.LogInformation("Hello World!");

var loggers = Logger.Factory.GetAll();
Logger.NotifyListeners(loggers);

Clone this wiki locally