Web API Tracing using Log4net dll

Hi,

In the below post we are going to learn about how we can using log4net.dll for tracing our webAPI project execution path.

First we are going to our own class which will be custom trace writer class .

add new class named “MyProjectTracer” to your project using Add New Item dialog

image

after that include the “System.Web.Http.Tracing” namespace to your class as below, this namespace provide the capabilities for tracing.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Http.Tracing;

 

namespace TracingAPI

{

    public class MyProjectTracer 

    {

         

    }

}

Now download the log4net dll ,you can download it from the below location and add its reference to your project.

http://logging.apache.org/log4net/download_log4net.cgi

After that open the web.config file add the below line in configSections

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

after adding the configSections will look like below


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

  

Now after the tag add the below lines.


    <appender name="FileAppender" type="log4net.Appender.FileAppender">

      <param name="File" value="D:\\TracingAPILog.txt"/>      

      <param name="AppendToFile" value="true"/>

      <layout type="log4net.Layout.PatternLayout">

        <param name="ConversionPattern" value="%d - %m%n"/>

      

    

    

      <level value="ALL"/>

      <appender-ref ref="FileAppender"/>

    

  

Go to the MyProjectTracer class we have created earlier and update the code as below.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net.Http;

using System.Web;

using System.Web.Http.Tracing;

using log4net;

using log4net.Config;

 

namespace TracingAPI

{

    public class MyProjectTracer:ITraceWriter

    {

        private static readonly ILog log = log4net.LogManager.GetLogger(typeof(MyProjectTracer));

        public void Trace(HttpRequestMessage request, string category, TraceLevel level,Action traceAction)

        {

            TraceRecord rec = new TraceRecord(request, category, level);

            traceAction(rec);

            WriteLog(rec);

        }

        public void WriteLog(TraceRecord rec)

        {

            String strLog = string.Format("{0};{1};{2};{3}",rec.Category, rec.Operator, rec.Operation, rec.Message);

            log.Info(strLog);

        }

    }

}

In the code we have innerited the ITraceWriter interface which provide a method to Trace to create a trace instance , further we have created an object log which will log every request to a file “TracingAPI.txt” which we have mentioned into the web.config file.

Now open the WebAPIConfig.cs or vb file and add the below line into the Register method of it. you alsso need to include the namespace “System.Web.Http.Tracing” to “WebApiConfig” class .

log4net.Config.XmlConfigurator.Configure();

            config.Services.Replace(typeof(ITraceWriter), new MyProjectTracer());

now we are ready ,rebuild your project and run it.browse any url for your project ,I am using the webApi sample application project template so I am browsing the below url.

image

after that open the “TracingAPILog.txt” file which is created in D directory .I got the below output.

2013-09-08 13:30:24,345 - System.Web.Http.Request;;;http://localhost:49280/Api/values/10

2013-09-08 13:30:24,361 - System.Web.Http.Controllers;DefaultHttpControllerSelector;SelectController;Route='controller:values,id:10'

2013-09-08 13:30:24,400 - System.Web.Http.Controllers;DefaultHttpControllerSelector;SelectController;Values

2013-09-08 13:30:24,401 - System.Web.Http.Controllers;HttpControllerDescriptor;CreateController;

2013-09-08 13:30:24,402 - System.Web.Http.Controllers;DefaultHttpControllerActivator;Create;

2013-09-08 13:30:24,406 - System.Web.Http.Controllers;DefaultHttpControllerActivator;Create;TracingAPI.Controllers.ValuesController

2013-09-08 13:30:24,407 - System.Web.Http.Controllers;HttpControllerDescriptor;CreateController;TracingAPI.Controllers.ValuesController

2013-09-08 13:30:24,408 - System.Web.Http.Controllers;ValuesController;ExecuteAsync;

2013-09-08 13:30:24,410 - System.Web.Http.Action;ApiControllerActionSelector;SelectAction;

2013-09-08 13:30:24,456 - System.Web.Http.Action;ApiControllerActionSelector;SelectAction;Selected action 'Get(Int32 id)'

2013-09-08 13:30:24,473 - System.Web.Http.ModelBinding;HttpActionBinding;ExecuteBindingAsync;

2013-09-08 13:30:24,479 - System.Web.Http.ModelBinding;ModelBinderParameterBinding;ExecuteBindingAsync;Binding parameter 'id'

2013-09-08 13:30:24,534 - System.Web.Http.ModelBinding;ModelBinderParameterBinding;ExecuteBindingAsync;Parameter 'id' bound to the value '10'

2013-09-08 13:30:24,537 - System.Web.Http.ModelBinding;HttpActionBinding;ExecuteBindingAsync;Model state is valid. Values: id=10

2013-09-08 13:30:24,543 - System.Web.Http.Action;ApiControllerActionInvoker;InvokeActionAsync;Action='Get(id=10)'

2013-09-08 13:30:24,545 - System.Web.Http.Action;ReflectedHttpActionDescriptor;ExecuteAsync;Invoking action 'Get(id=10)'

2013-09-08 13:30:24,561 - System.Web.Http.Action;ReflectedHttpActionDescriptor;ExecuteAsync;Action returned 'value'

2013-09-08 13:30:24,570 - System.Net.Http.Formatting;DefaultContentNegotiator;Negotiate;Type='String', formatters=[JsonMediaTypeFormatterTracer, XmlMediaTypeFormatterTracer, FormUrlEncodedMediaTypeFormatterTracer, FormUrlEncodedMediaTypeFormatterTracer]

2013-09-08 13:30:24,584 - System.Net.Http.Formatting;XmlMediaTypeFormatter;GetPerRequestFormatterInstance;Obtaining formatter of type 'XmlMediaTypeFormatter' for type='String', mediaType='application/xml; charset=utf-8'

2013-09-08 13:30:24,585 - System.Net.Http.Formatting;XmlMediaTypeFormatter;GetPerRequestFormatterInstance;Will use same 'XmlMediaTypeFormatter' formatter

2013-09-08 13:30:24,586 - System.Net.Http.Formatting;DefaultContentNegotiator;Negotiate;Selected formatter='XmlMediaTypeFormatter', content-type='application/xml; charset=utf-8'

2013-09-08 13:30:24,589 - System.Web.Http.Action;ApiControllerActionInvoker;InvokeActionAsync;

2013-09-08 13:30:24,590 - System.Web.Http.Controllers;ValuesController;ExecuteAsync;

2013-09-08 13:30:24,591 - System.Web.Http.Request;;;Content-type='application/xml; charset=utf-8', content-length=unknown

2013-09-08 13:30:24,607 - System.Net.Http.Formatting;XmlMediaTypeFormatter;WriteToStreamAsync;Value='value', type='String', content-type='application/xml; charset=utf-8'

2013-09-08 13:30:24,612 - System.Net.Http.Formatting;XmlMediaTypeFormatter;WriteToStreamAsync;

2013-09-08 13:30:24,614 - System.Web.Http.Controllers;ValuesController;Dispose;

2013-09-08 13:30:24,614 - System.Web.Http.Controllers;ValuesController;Dispose;

It gives the detailed output how the WebApi process your request .

Hope you find this post useful, Thanks for reading. 🙂

Advertisements

2 thoughts on “Web API Tracing using Log4net dll

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s