Skip to content

.NET Core Web App

Catalin Gavan edited this page Nov 23, 2021 · 20 revisions

These steps describe how to install and configure KissLog for a .NET Core Web Application.

A full working example can be found here.

By following the install instructions, you will will:

  • register KissLog as Microsoft.Extensions.Logging.ILogger<> adapter
  • configure KissLog to capture and log all the unhandled exceptions
  • configure KissLog to capture all the HTTP properties (User-Agent, QueryString, FormData, Headers, StatusCode, etc.)
  • register LocalTextFileListener listener which will save the captured data to logs folder

Instructions

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

namespace AspNetCore_WebApp
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHttpContextAccessor();

            // Optional. Register IKLogger only if you use KissLog.IKLogger instead of Microsoft.Extensions.Logging.ILogger<>
            services.AddScoped<IKLogger>((provider) => Logger.Factory.Get());

            services.AddLogging(logging =>
            {
                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 });
                    };
                });
            });

            services.AddControllersWithViews();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthorization();
            app.UseSession();

            app.UseKissLogMiddleware(options => ConfigureKissLog(options));

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }

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

Write logs

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

using Microsoft.Extensions.Logging;

namespace AspNetCore_WebApp.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            _logger.LogTrace("Trace log");

            return View();
        }
    }
}