From 4b31d209dab850ee48c76dc222d6008470d46c1f Mon Sep 17 00:00:00 2001 From: anoyes Date: Thu, 20 Dec 2018 09:34:02 -0800 Subject: [PATCH] Emit valid json for unprintable characters --- flow/JsonTraceLogFormatter.cpp | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/flow/JsonTraceLogFormatter.cpp b/flow/JsonTraceLogFormatter.cpp index 70f5cf9970..8574f35a80 100644 --- a/flow/JsonTraceLogFormatter.cpp +++ b/flow/JsonTraceLogFormatter.cpp @@ -45,14 +45,22 @@ const char* JsonTraceLogFormatter::getFooter() { namespace { -void escapeString(std::stringstream& ss, const std::string source) { +void escapeString(std::stringstream& ss, const std::string& source) { for (auto c : source) { if (c == '"') { ss << "\\\""; } else if (c == '\\') { ss << "\\\\"; - } else { + } else if (c == '\n') { + ss << "\\n"; + } else if (c == '\r') { + ss << "\\r"; + } else if (isprint(c)) { ss << c; + } else { + constexpr char hex[] = "0123456789abcdef"; + int x = int{ static_cast(c) }; + ss << "\\x" << hex[x / 16] << hex[x % 16]; } } }