title: Log every request to web api method to file
body: <p>My requirements are to add logging to every request and response and errors to a file. I have tried this,</p>
  
  <pre><code>public class LogRequestAndResponseHandler : DelegatingHandler
  {
      private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  
      protected override async Task&lt;HttpResponseMessage&gt; SendAsync(
          HttpRequestMessage request, CancellationToken cancellationToken)
      {
          // log request body
          string requestBody = await request.Content.ReadAsStringAsync();
          Log.Info(requestBody);
  
          // let other handlers process the request
          var result = await base.SendAsync(request, cancellationToken);
  
          if (result.Content != null)
          {
              // once response body is ready, log it
              var responseBody = await result.Content.ReadAsStringAsync();
              Log.Info(responseBody);
          }
  
          return result;
      }
  }
  </code></pre>
  
  <p>Added this it to WebApiConfig of MVC5 as following,</p>
  
  <pre><code>public static class WebApiConfig
  {
      public static void Register(HttpConfiguration config)
      {
          // Web API configuration and services
  
          log4net.Config.XmlConfigurator.Configure();
  
          config.MessageHandlers.Add(new LogRequestAndResponseHandler());
  
          // Web API routes
          config.MapHttpAttributeRoutes();
  
          config.Routes.MapHttpRoute(
              name: "DefaultApi",
              routeTemplate: "api/{controller}/{id}",
              defaults: new { id = RouteParameter.Optional }
          );
      }
  }
  </code></pre>
  
  <p>Web config has this section,</p>
  
  <pre><code>  &lt;log4net&gt;
      &lt;!-- file appender --&gt;
      &lt;appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"&gt;
        &lt;file value="C:/logs/my_log_file.log"/&gt;
        &lt;appendToFile value="true"/&gt;
        &lt;rollingStyle value="Date"/&gt;
        &lt;maxSizeRollBackups value="30"/&gt;
        &lt;datePattern value=".yyyy-MM-dd"/&gt;
        &lt;staticLogFileName value="true"/&gt;
        &lt;layout type="log4net.Layout.PatternLayout"&gt;
          &lt;conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/&gt;
        &lt;/layout&gt;
      &lt;/appender&gt;
      &lt;root&gt;
        &lt;level value="DEBUG"/&gt;
        &lt;appender-ref ref="RollingFileAppender"/&gt;
      &lt;/root&gt;
    &lt;/log4net&gt;
  </code></pre>
  
  <p>Nothing is being added to file and there are no errors, is there anything I am doing wrong, it creates the file but no logging ever ?</p>