Monday, December 31, 2012

ASP.NET MVC 4.0 Web API - How to log all method calls?

Trace logs are very important for debugging. In Web API you have a very good option to have your own trace by using ITraceWriter interface (read here). However you can simply write your own message handler to implement a very simple logger to log all Web API method calls. A message handler is a class that accepts a request and returns a response (see here). This class after registration will start working in the HTTP pipeline. What you can do is simply using a code like this:

    public class LogHandler : DelegatingHandler

        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,        
                                                      CancellationToken cancellationToken)
            return base.SendAsync(request, cancellationToken).ContinueWith((task) =>
                HttpResponseMessage response = task.Result;
                DataAccessManager.Instance.LogInsert(new Log()
                        LogDate = DateTime.Now,
                        LogEntry = request.ToString()
                return response;

  • In the above code calling request.ToString() returns the representation of the request object in JSON format. 
  • I call LogInsert to insert my log into a database table. You may have your own implementation however.

After creating your Message Handler you need to register it in your WebApiConfig:

public static class WebApiConfig
        public static void Register(HttpConfiguration config)

            config.MessageHandlers.Add(new LogHandler());



And your log DTO can be very simple like this:

public partial class Log
   public long ID {set; get;}
   public System.Nullable<System.DateTime> LogDate {set; get;}
   public string LogEntry {set; get;}

That's it. Hope this help you to implement your own logger very fast.
Enjoy the holidays and Happy new year 2013!


  1. cool man! well done!! works perfect!! thank you very much!!!