How to add logging in ASP.NET

By FoxLearn 11/1/2024 2:11:12 PM   43
Here is code snippet that writes some text to log.txt file in web root folder.

ASP.NET WebForms

To add logging in ASP.NET WebForms, you can follow these steps:

You can create a simple method to log messages to a text file.

public partial class WebPage1 : System.Web.UI.Page
{
    private void Logging()
    {
        // Ad hoc logging 
        using (var wr = new StreamWriter(Server.MapPath("~/log.txt"), true))
        {
            wr.WriteLine("log data here");  
        }
    }
}

The Page.Server.MapPath() method in ASP.NET WebForms is used to convert a virtual path to its corresponding physical file path. Once the physical path is determined, logging to a file becomes straightforward.

ASP.NET MVC

The Controller.Server.MapPath() method in ASP.NET MVC is used to obtain the actual physical file path corresponding to a given virtual path.

For example:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        // Ad hoc logging 
        using (var wr = new StreamWriter(Server.MapPath("~/log.txt"), true))
        {
            wr.WriteLine("log data here");
        } 
        return View();
    }
}

ASP.NET Core

ASP.NET Core utilizes the ILogger logging mechanism, which is generally recommended. However, unlike previous frameworks, it doesn't have Server.MapPath().

As a workaround, you can use IWebHostEnvironment.ContentRootPath or IWebHostEnvironment.WebRootPath. To implement this, inject the IWebHostEnvironment parameter into the controller's constructor, store it in a field, and then access the physical path of the root folder using these properties.

For example:

public class HomeController : Controller
{
    private readonly ILogger<HomeController> _logger;
    private IWebHostEnvironment _env;
 
    public HomeController(ILogger<HomeController> logger, IWebHostEnvironment env)
    {
        _logger = logger;
        _env = env;
    }
 
    public IActionResult Index()
    {
        // Ad hoc logging 
        using (var wr = new StreamWriter(Path.Combine(_env.ContentRootPath, "log.txt"), true))
        {
            wr.WriteLine("log data here");
        } 
        return View();
    }
}