11

Given a simple protobuf message with one string field :

message Sample{
    required string msg = 1;
}

and a sample code to print it :

Sample message = Sample.newBuilder()
    .setMsg("some text")
    .build();

System.out.println(message);
System.out.println(message);
System.out.println(message);

result of this output will be :

msg: "some text"

msg: "some text"

msg: "some text"

There is '\n' line break with each message (actually each field). This is not good for loggers apparently.

Serializing this with Gson is even worse as gson will serialize lot of other fields that were generated...

{"bitField0_":1,"msg_":"some text","memoizedIsInitialized":1,"unknownFields":{"fields":{}},"memoizedSize":-1,"memoizedHashCode":0}

How do we convert protobuf message to a single string without line breaks?

vach
  • 10,571
  • 12
  • 68
  • 106

1 Answers1

18

The toString() on a message generates a empty line after each message, to make the reading/separation easier.

For logging purpose of a whole message you should use TextFormat.shortDebugString(message). If you only want to log specific fields use the message.get...() methods.

SubOptimal
  • 22,518
  • 3
  • 53
  • 69
  • 2
    Note that `TextFormat.shortDebugString(message)` will throw NPE if message is null. – shad Jul 14 '18 at 01:14
  • You also can't do this trick for already generated code and libraries. – Praytic Sep 22 '21 at 15:17
  • this is a sub optimal thing to do in a library because if you are dealing with protobuf messages as plain Objects and logging them then you will get ugly log messages, its beyond me why would library devs do this – vach Apr 24 '22 at 18:17