C# Tips

C# Tip Article

Ad hoc logging in ASP.NET

I needed to add quick and dirty ad hoc log to staging/test web server. For quick ad hoc logging, I felt like DB logging or Windows Event logging was a little heavy. So I went for text file logging. Here is code snippet that writes some text to log.txt file in web root folder.


ASP.NET WebForms

Page.Server.MapPath() method in ASP.NET WebForms returns physical file path for the virtual path. Once the physical file path is obtained, writing the log to the file is simple.

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");  
		}
	}
}

ASP.NET MVC

Controller.Server.MapPath() method in ASP.NET MVC returns actual file path for the virtual path.

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 uses ILogger logging mechanism and probably it is good idea to use it. But you might want to use the same approach as above. However, ASP.NET Core does not have Server.MapPath(). As a workaround, though, you can use IWebHostEnvironment.ContentRootPath (or IWebHostEnvironment.WebRootPath) as below. To use it, inject IWebHostEnvironment parameter in Controller constructor and save it to field. Then use ContentRootPath or WebRootPath property to get physical path of root folder.

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();
	}
}