[lldb][lldb-vscode] Pretty print JSON to log files

This makes anlysing test failures much more easy.

For SendJSON this is simple, just use llvm::format instead.

For GetNextObject/ReadJSON it's a bit more tricky.
* Print the "Content-Length:" line in ReadJSON, but not the json.
* Back in GetNextObject, if the JSON doesn't parse, it'll be
  printed as a normal string along with an error message.
* If we didn't error before, we have a JSON value so we pretty print it.
* Finally, if it isn't an object we'll log an error for that,
  not including the JSON.

Before:
```
<--
Content-Length: 81

{"command":"disconnect","request_seq":5,"seq":0,"success":true,"type":"response"}
```

After:
```
<--
Content-Length: 81

{
  "command": "disconnect",
  "request_seq": 5,
  "seq": 0,
  "success": true,
  "type": "response"
}
```

There appear to be some responses that include strings that are themselves JSON,
and this won't pretty print those but I think it's still worth doing.

Reviewed By: wallace

Differential Revision: https://reviews.llvm.org/D156979
This commit is contained in:
David Spickett 2023-08-03 09:01:54 +00:00
parent bdeb35bda4
commit 165f45a877

View File

@ -89,12 +89,6 @@ void VSCode::SendJSON(const std::string &json_str) {
output.write_full(llvm::utostr(json_str.size()));
output.write_full("\r\n\r\n");
output.write_full(json_str);
if (log) {
*log << "<-- " << std::endl
<< "Content-Length: " << json_str.size() << "\r\n\r\n"
<< json_str << std::endl;
}
}
// Serialize the JSON value into a string and send the JSON packet to
@ -105,7 +99,14 @@ void VSCode::SendJSON(const llvm::json::Value &json) {
strm << json;
static std::mutex mutex;
std::lock_guard<std::mutex> locker(mutex);
SendJSON(strm.str());
std::string json_str = strm.str();
SendJSON(json_str);
if (log) {
*log << "<-- " << std::endl
<< "Content-Length: " << json_str.size() << "\r\n\r\n"
<< llvm::formatv("{0:2}", json).str() << std::endl;
}
}
// Read a JSON packet from the "in" stream.
@ -129,11 +130,8 @@ std::string VSCode::ReadJSON() {
if (!input.read_full(log.get(), length, json_str))
return json_str;
if (log) {
*log << "--> " << std::endl
<< "Content-Length: " << length << "\r\n\r\n"
<< json_str << std::endl;
}
if (log)
*log << "--> " << std::endl << "Content-Length: " << length << "\r\n\r\n";
return json_str;
}
@ -523,6 +521,11 @@ PacketStatus VSCode::GetNextObject(llvm::json::Object &object) {
}
return PacketStatus::JSONMalformed;
}
if (log) {
*log << llvm::formatv("{0:2}", *json_value).str() << std::endl;
}
llvm::json::Object *object_ptr = json_value->getAsObject();
if (!object_ptr) {
if (log)