dbus: Truncate strings in dbus::Message::ToString() if too long

To prevent long strings from polluting logs.

BUG=131261
TEST=added a unit test

Review URL: https://chromiumcodereview.appspot.com/10537033

git-svn-id: svn://svn.chromium.org/chrome/trunk/src@141021 0039d316-1c4b-4281-b951-d872f2087c98
diff --git a/dbus/message.cc b/dbus/message.cc
index 2caf543e..fd7c077 100644
--- a/dbus/message.cc
+++ b/dbus/message.cc
@@ -155,7 +155,17 @@
         std::string value;
         if (!reader->PopString(&value))
           return kBrokenMessage;
-        output += indent + "string \"" + value + "\"\n";
+        // Truncate if the string is longer than the limit.
+        const size_t kTruncateLength = 100;
+        if (value.size() < kTruncateLength) {
+          output += indent + "string \"" + value + "\"\n";
+        } else {
+          std::string truncated;
+          TruncateUTF8ToByteSize(value, kTruncateLength, &truncated);
+          base::StringAppendF(&truncated, "... (%"PRIuS" bytes in total)",
+                              value.size());
+          output += indent + "string \"" + truncated + "\"\n";
+        }
         break;
       }
       case OBJECT_PATH: {
diff --git a/dbus/message.h b/dbus/message.h
index 0b9834d..38887f8 100644
--- a/dbus/message.h
+++ b/dbus/message.h
@@ -114,7 +114,8 @@
   uint32 GetReplySerial();
 
   // Returns the string representation of this message. Useful for
-  // debugging.
+  // debugging. The output is truncated as needed (ex. strings are truncated
+  // if longer than a certain limit defined in the .cc file).
   std::string ToString();
 
  protected:
diff --git a/dbus/message_unittest.cc b/dbus/message_unittest.cc
index d78d90f2..10835a29 100644
--- a/dbus/message_unittest.cc
+++ b/dbus/message_unittest.cc
@@ -613,3 +613,18 @@
   EXPECT_EQ("", message->GetErrorName());
   EXPECT_EQ("", message->GetSender());
 }
+
+TEST(MessageTest, ToString_LongString) {
+  const std::string kLongString(1000, 'o');
+
+  scoped_ptr<dbus::Response> message(dbus::Response::CreateEmpty());
+  dbus::MessageWriter writer(message.get());
+  writer.AppendString(kLongString);
+
+  ASSERT_EQ("message_type: MESSAGE_METHOD_RETURN\n"
+            "signature: s\n\n"
+            "string \"oooooooooooooooooooooooooooooooooooooooooooooooo"
+            "oooooooooooooooooooooooooooooooooooooooooooooooooooo... "
+            "(1000 bytes in total)\"\n",
+            message->ToString());
+}