2012-04-28 82 views
3

我想知道是否有人能告訴我如何從我的wcf rest服務記錄一個簡單的請求/響應。WCF/REST日誌記錄

我自己用的LOCALMACHINE控制檯應用程序託管:

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string baseAddress = "http://" + Environment.MachineName + ":8000/Service"; 
      ServiceHost host = new ServiceHost(typeof(RawDataService), new Uri(baseAddress)); 
      WebHttpBinding binding = new WebHttpBinding(); 
      //binding.Security.Mode = WebHttpSecurityMode.Transport; 
      host.AddServiceEndpoint(typeof(IReceiveData), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior()); 
      host.Open(); 
      Console.WriteLine("Host opened"); 
      Console.ReadLine(); 
     } 
    } 
} 

我真的很希望所有將需要的東西加入到託管控制檯應用程序。我嘗試了下面這個,但它有點混亂http://blogs.msdn.com/b/carlosfigueira/archive/2011/04/19/wcf-extensibility-message-inspectors.aspx

只是爲了說明我沒有使用任何app.config或web.config文件。

編輯:

我也不能使用任何第三方產品。

回答

0

您是在談論用於調試目的的日誌記錄還是用於在現場服務中進行監控?

如果您正在調試,只需打開WCF跟蹤即可。它會產生一個非常全面的日誌,並且有一個很好的免費工具來查看作爲Windows SDK一部分的日誌 - 我假定當你說你不能使用第三方產品時它不包含內置的.Net和Windows SDK功能...

http://msdn.microsoft.com/en-us/library/ms733025.aspx

0

處理此問題的常見方法是使用Castle動態代理庫的面向方面編程(AOP)。這個想法是,你可以用一個動態類來修飾/代理你的服務實現,該動態類可以攔截服務上調用的每一種方法。無論您的服務使用何種方法,它們都會被您的代理「截獲」,併發送到單一方法,您可以在其中記錄所需內容,然後即可完成原始呼叫。下面是什麼,看起來像一個快速的樣品:

public class LoggingInterceptor : IInterceptor 
{ 
    // No matter what service method is called, it's funneled through here. 
    public void Intercept(IInvocation call) 
    { 
     MyLogger.Info("Starting call: " + call.Method.Name); 

     // Actually invoke whatever method was originally called 
     call.Proceed(); 

     MyLogger.Info("Finished call: " + call.Method.Name); 
    } 
} 

現在你需要創建一個使用這個攔截所有的方法調用的服務類的代理。你幾乎可以達到和抽象爲必要的,但是這是基本的JIST:

using Castle.DynamicProxy; 
... 

// Create your service object and then create a dynamic proxy of the object 
// that will inject your logging interceptor logic. 
ProxyGenerator generator = new ProxyGenerator(); 
RawDataService service = new RawDataService(); 
RawDataService proxy = generator.CreateClassProxyWithTarget<RawDataService>(
    service, 
    new LoggingInterceptor()); 

// Register your proxy object, not the raw service w/ WCF 
WebServiceHost host = new WebServiceHost(proxy, new Uri(baseAddress)); 
... rest of your code as it was ... 

現在你RawDataService所做的任何電話將通過攔截()方法首先,當它調用繼續()實際實現的服務邏輯會發生。您可以更新攔截器來處理異常,根據需要包含StopWatch和日誌參數,但這是基本思路。

我的例子向你展示了設置它的蠻力方式。 「更清潔」的解決方案是使用IoC來創建你的服務實例/代理,但是這應該讓你的代碼現在就做你想要的。如需進一步閱讀,請使用其AOP掛鉤連接到Castle project's tutorial

+0

在你的日誌記錄攔截器類,一定要包括'使用Castle.DynamicProxy' - 記住這是第三部分庫,所以如果你沒有它,你可以從NuGet獲得或直接從[Castle Project](http://www.castleproject.org/castle/download.html)下載。您需要爲'Castle.Core'和'Castle.Windsor'的項目添加引用。 – 2012-04-28 16:12:50

+0

Ahh抱歉Rob我無法使用任何第三方產品。我的錯誤是沒有在問題中提到這一點。現在會更新。 – 2012-04-28 16:14:41