Created
October 27, 2014 14:35
-
-
Save darrelmiller/28221417620db2973a25 to your computer and use it in GitHub Desktop.
Coloured Request/Response console logger
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ConsoleRequestLogger : DelegatingHandler | |
{ | |
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) | |
{ | |
Console.ForegroundColor = ConsoleColor.Cyan; | |
Console.WriteLine("> {0} {1}",request.Method,request.RequestUri.GetComponents(UriComponents.PathAndQuery, UriFormat.SafeUnescaped)); | |
ProcessHeader(request.Headers, (name, value) => Console.WriteLine("> {0}: {1}", name, value)); | |
if (request.Content != null) | |
{ | |
ProcessHeader(request.Content.Headers, (name,value)=>Console.WriteLine("> {0}: {1}", name, value)); | |
} | |
var response = await base.SendAsync(request, cancellationToken); | |
Console.ForegroundColor = ConsoleColor.Green; | |
Console.WriteLine("< {0} {1}", (int)response.StatusCode, response.ReasonPhrase); | |
ProcessHeader(response.Headers, (name, value) => Console.WriteLine("< {0}: {1}", name, value)); | |
if (response.Content != null) | |
{ | |
ProcessHeader(response.Content.Headers, (name, value) => Console.WriteLine("< {0}: {1}", name, value)); | |
Console.WriteLine(); | |
var body = await response.Content.ReadAsStringAsync(); | |
if (body.Length > 3000) | |
{ | |
body = body.Substring(0, 3000) + "..."; | |
} | |
Console.WriteLine(body); | |
} | |
Console.ForegroundColor = ConsoleColor.Yellow; | |
Console.WriteLine("-------------------------------------------------------------------------------------"); | |
Console.ResetColor(); | |
return response; | |
} | |
private static void ProcessHeader(HttpHeaders headers, Action<string,string> headerAction) | |
{ | |
foreach (var httpRequestHeader in headers) | |
{ | |
foreach (var headerValue in httpRequestHeader.Value) | |
{ | |
headerAction(httpRequestHeader.Key, headerValue); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment