Search code examples
asp.net-mvcserilog

How do I log from a .net 4.8 mvc controller using serilog?


I'm new to mvc and I'm trying to get logging to work I don't know how to write to log from different controlers Logging from global.asax -> Application_Start() here logging works.

I have installed following nuget packages:

<package id="Serilog" version="2.12.0" targetFramework="net48" />
<package id="Serilog.Sinks.Console" version="4.1.0" targetFramework="net48" />
<package id="Serilog.Sinks.File" version="5.0.0" targetFramework="net48" />
<package id="SerilogWeb.Classic" version="5.1.66" targetFramework="net48" />
<package id="SerilogWeb.Classic.Mvc" version="2.1.25" targetFramework="net48" />

Global.asax file:

public class App : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        var log = new LoggerConfiguration()
        .WriteTo.File(System.Web.Hosting.HostingEnvironment.MapPath("~/bin/Logs/log.txt"))
        .CreateLogger();
        log.Information("Hello - Application_Start"); //Works
    }
}

Controller 1

public class TestController : Controller
{
    //setup log or what to do??
    public ActionResult Index()
    {
        log.Information("Log sample 1")
        return View();
    }
}

Controller 2

public class AnotherTestController : Controller
{
    //setup log or what to do??
    public ActionResult Index()
    {
        log.Information("Log sample 2")
        return View();
    }
}

A file in appcode folder

public static class TSTUtil
{
    //This is not a controller but how to setup log or what to do??
    public static string GetHelp()
    {
        log.Information("Log sample 3")
    }
}

Solution

  • First add the static class config of the serilog

    public class App : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            var log = new LoggerConfiguration()
            .WriteTo.File(System.Web.Hosting.HostingEnvironment.MapPath("~/bin/Logs/log.txt"))
            .CreateLogger();
    Log.Logger=log;
            Log.Logger.Information("Hello - Application_Start"); //Works
        }
    

    }

    Then anywhere you can just call it:

    public class TestController : Controller
    {
        //setup log or what to do??
        public ActionResult Index()
        {
            Log.Logger.Information("Log sample 1")
            return View();
        }
    }