ASP.NET Log requests and responses
At work we have setup a mock api using ASP.NET (.NET 4.7.1) that mocks the interface of a third party service that is not yet available. To allow our testers to see what the requests and responses look like when the service is called we used Serilog and the File sink to instrument the mock api. I love Serilog, but the testers are under a bit of time pressure and asked if we could write a separate log that only showed the response and request data and nothing else - as the Serilog files were a bit busy on Verbose. They also asked if we could format the json requests and responses to make it easier to validate.
I cobbled together the following.
I created a DelegatingHandler that I registered as a MessageHandler to intercept all requests. For the logging (RequestResponseLogger) I used a BlockingCollection which I used as a queue. Using GetConsumingEnumerable converting it to an observable and subscribing to changes using Rx.NET (v3.1.1). In the subscribe I simply appended a collection of strings to a file using File.AppendAllLines. This makes it nice and threadsafe without any locking.
In the HttpLoggingHandler.SendAsync I start by creating a list of strings and then append the 'lines' I want to log to this list. After logging what I needed from the request and response to the contents list I enqueue this to the RequestResponseLogger. This keeps all the logged lines for a request together in the log file making it even easier for the testers.
Note: there is no error handling here - exceptions are logged elsewhere, the current implementation is purely there to log happy path situations.
One last thing to note, is the 'pretty printing' of json in the log. This was done with:
result = JToken.Parse(result).ToString(Formatting.Indented);
HttpLoggingHandler List AddContent Remember to register the handler: