Implementing logging for ASP.NET Web API with log4net.

We will implement logging of actions in controllers and catch all exceptions in application and log them.

First, go to the visual studio and create ASP.NET Web API project.
Then, using Nuget Package Manager add log4net to this project.

Add following line

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

to your Global.asax or Startup.cs file:

[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace WebAPILogging
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

Then add following line

log4net.Config.XmlConfigurator.Configure();

to the WebConfig.cs file:

namespace WebAPILogging
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            log4net.Config.XmlConfigurator.Configure(); 

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

Now, we have to configure log4net in the web.config.

First, add following config section

 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

to the configSections element.

Then, add log4net section to the configuration element.

<log4net>
  <!-- file appender -->
  <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="C:/logs/my_log_file.log"/>
    <appendToFile value="true"/>
    <rollingStyle value="Date"/>
    <maxSizeRollBackups value="30"/>
    <datePattern value=".yyyy-MM-dd"/>
    <staticLogFileName value="true"/>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger - %message%newline"/>
    </layout>
  </appender>
  <root>
    <level value="DEBUG"/>
    <appender-ref ref="RollingFileAppender"/>
  </root>
</log4net>

Configuration is finished. Now we need to log some request to see the results. Let’s add Logger object to one of your controllers.

private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

And right after that add the

Log.Debug("GET Request traced");

line to one of the actions of this controller(I added it to GET action method)
Now, my controller looks like that:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using log4net;

namespace TestLog4net.Controllers
{
    public class ValuesController : ApiController
    {
        private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        // GET api/values
        public IEnumerable<string> Get()
        {
            Log.Debug("GET Request traced");
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/values
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        public void Delete(int id)
        {
        }
    }
}

That’s all. Now after we compile and run our project we can go to the controller/action method that we modified and we will see that file C:/logs/my_log_file.log has been created with a record from our logger. In the next post I’ll use this logger in action filter to trace all controllers/actions from one place.

Used resource:
http://danmo.github.io/blog/articles/WebAPI-Exception-Handling-And-Logging/WebAPI-Exception-Handling-And-Logging

Share this post:Tweet about this on TwitterShare on Facebook1Share on LinkedIn0Share on Google+0Share on Reddit0Email this to someoneDigg this
  • This was a fantastic resource. You simplified everything and laid it out well, so I was able to incorporate log4net simply and easily. Thanks!