Forked from darrelmiller/gist:28221417620db2973a25
Last active
August 29, 2015 14:08
-
-
Save mahizsas/1fa0a57c8cabef38c7e6 to your computer and use it in GitHub Desktop.
Colored Console MesageHanlder
This file contains hidden or 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