Custom file based logging in ASP.NET MVC
Posted: (EET/GMT+2)
If you are developing ASP.NET MVC applications, then especially in the beginning, you might wish to know exactly which route your requests are handled with. Or, if you are using AJAX a lot, verifying the calls on the server side can be difficult unless you can attach Visual Studio to your application.
Luckily, you can use so-called action filters in your MVC applications. Actions filters are attributes that implement the IActionFilter interface and descend from the ActionFilterAttribute class. This interface supports two methods, one of which is suitable for logging all the calls that come to a certain action method or a controller as a whole.
Here is a simple code example of a class that is able to implement file based logging:
using System.IO;
using System.Web.Routing;
...
public class LogCallAttribute : ActionFilterAttribute
{
private void LogMessageToFile(string msg)
{
const string LogFileName =
@"C:\Temp\MyMvcApp.log";
File.AppendAllText(LogFileName,
DateTime.Now.ToLocalTime() + ": "
+ msg + ".\r\n");
}
public override void OnActionExecuting(
ActionExecutingContext filterContext)
{
RouteValueDictionary route =
filterContext.RouteData.Values;
string location =
route["controller"] + "/" +
route["action"];
LogMessageToFile("In action " + location);
}
}
With this class in your MVC project, you can then utilize the attribute in two ways, at the controller level or the action method level like this:
[LogCall]
public class HomeController : Controller
...
[LogCall]
public ActionResult About()
{
return View();
}
Sounds simple? It is!