Skip to content

ASP.NET MVC

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

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

A full working example can be found here.

By following the install instructions, you will:

  • 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.AspNet.Mvc
  1. Update Global.asax
using KissLog;
using KissLog.AspNet.Mvc;
using KissLog.AspNet.Web;
using KissLog.Listeners.FileListener;

namespace AspNet.Mvc
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            // Add KissLog exception filter
            GlobalFilters.Filters.Add(new KissLogWebMvcExceptionFilterAttribute());

            ConfigureKissLog();
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();
            if (exception != null)
            {
                var logger = Logger.Factory.Get();
                logger.Error(exception);

                if (logger.AutoFlush() == false)
                {
                    Logger.NotifyListeners(logger);
                }
            }
        }

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

        // Register HttpModule
        public static KissLogHttpModule KissLogHttpModule = new KissLogHttpModule();

        public override void Init()
        {
            base.Init();

            KissLogHttpModule.Init(this);
        }
    }
}

Write logs

Logs can be written using KissLog.IKLogger interface.

To receive the logger instance, use Logger.Factory.Get() factory method.

For web applications, Logger.Factory.Get() will return the same logger instance shared across the HTTP request.

using KissLog;
using System.Web.Mvc;

namespace AspNet.Mvc.Controllers
{
    public class HomeController : Controller
    {
        private readonly IKLogger _logger;
        public HomeController()
        {
            _logger = Logger.Factory.Get();
        }

        public ActionResult Index()
        {
            _logger.Trace("Trace message");

            return View();
        }
    }
}