I want to log the response content of requests to my service, and I'm wondering what is the best way to go about it. Here are my specific requirements:
- Response content should be serialized ONCE in the entire pipeline.
- Response content only, no headers, etc.
- Logging is applied to subset of all APIs.
In short, I want to add logging for a subset of all APIs while adding the least possible amount of overhead. The reason I don't want to add logging for all APIs is because we have a load balancer hitting one of the APIs repeatedly, and it is not useful for us to log those requests.
The only examples I have seen that meet the first requirement use IHttpModule and replace the filter (e.g. Logging raw HTTP request/response in ASP.NET MVC & IIS7). However using IHttpModule will log all API responses, which does not meet requirement 3. Also replacing the filter will not easily meet requirement 2 (where do the headers end and content begin?).
Due to requirements 2 and 3, I am leaning towards ActionFilterAttribute and IFilterProvider for logging (e.g. http://haacked.com/archive/2011/04/25/conditional-filters.aspx/), but I haven't seen a way to meet requirement 1 in that scenario.
A hack would be to return the HTTP content as serialized StringContent instead of ObjectContent, but this violates features in ASP.NET such as choosing your AcceptType.