Skip to content

Commit

Permalink
Pretty print requests and responses for easier troubleshooting
Browse files Browse the repository at this point in the history
  • Loading branch information
icnocop committed Oct 14, 2023
1 parent 85b1d28 commit 505dd5e
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/AzurePipelines.TestLogger/ApiClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ internal virtual async Task<string> SendAsync(HttpMethod method, string endpoint

if (Verbose)
{
Console.WriteLine($"Request:\n{method} {requestUri}\n{body}\n\nResponse:\n{response.StatusCode}\n{responseBody}");
Console.WriteLine($"Request:\n{method} {requestUri}\n{body.Indented()}\n\nResponse:\n{response.StatusCode}\n{responseBody.Indented()}\n");
}

try
Expand Down
41 changes: 41 additions & 0 deletions src/AzurePipelines.TestLogger/Json/JsonExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,5 +83,46 @@ private static string JsonEscape(string value)

return sb.ToString();
}

/// <summary>
/// Indent JSON string.
/// </summary>
/// <param name="input">The JSON string.</param>
/// <returns>The indented JSON string.</returns>
public static string Indented(this string input)
{
int level = 0;
StringBuilder result = new StringBuilder();

for (int i = 0; i < input.Length; i++)
{
char c = input[i];

if (c == '{' || c == '[')
{
result.Append(c);
result.AppendLine();
result.Append(new string(' ', ++level * 2));
}
else if (c == '}' || c == ']')
{
result.AppendLine();
result.Append(new string(' ', --level * 2));
result.Append(c);
}
else if (c == ',')
{
result.Append(c);
result.AppendLine();
result.Append(new string(' ', level * 2));
}
else
{
result.Append(c);
}
}

return result.ToString();
}
}
}

0 comments on commit 505dd5e

Please sign in to comment.