I needed to have the WCF message identifier in every log message because I needed to correlate the log messages from a particular WCF call.

The best way to achieve this with log4net is to use context properties.

Since I’m already using Unity and Interception on my WCF Services, I’ve decided to implement a custom Call Hander


namespace CustomCallHandlers
{
 using System;
 using Microsoft.Practices.Unity.InterceptionExtension;

 /// <summary>
 /// Call Handler to setup wcf message id in log4net context
 /// </summary>
 public class ServiceCallHandler : ICallHandler
 {
 /// <summary>
 /// The message identifier
 /// </summary>
 private const string MessageIdKey = "MessageId";

 /// <summary>
 /// Initializes a new instance of the <see cref="ServiceCallHandler"/> class.
 /// </summary>
 /// <param name="order">The call handler's execution order.</param>
 public ServiceCallHandler(int order)
 {
  this.Order = order;
 }

 /// <summary>
 /// Gets or sets the order.
 /// </summary>
 public int Order { get; set; }

 /// <summary>
 /// Invokes the specified input.
 /// </summary>
 /// <param name="input">The input.</param>
 /// <param name="getNext">The get next.</param>
 /// <returns>The method return for the nexte invocation</returns>
 public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
 {
  if ((System.ServiceModel.OperationContext.Current != null) &&
      (System.ServiceModel.OperationContext.Current.IncomingMessageHeaders != null))
  {
   if (System.ServiceModel.OperationContext.Current.IncomingMessageHeaders.MessageId != null)
   {
    string messageId = System.ServiceModel.OperationContext.Current.IncomingMessageHeaders.MessageId.ToString();
    log4net.ThreadContext.Properties[MessageIdKey] = messageId == "(null)" ? Guid.NewGuid().ToString() : messageId;
   }
  }

  IMethodReturn resultado = getNext()(input, getNext);

  // Cleaning
  log4net.ThreadContext.Properties[MessageIdKey] = null;

  return resultado;
  }
 }
}

If you want to see how to configure log4net appenders to write custom properties check this post.

 

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here