Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting protobuf for logs

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?

like image 883
vach Avatar asked Oct 13 '15 06:10

vach


1 Answers

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.

like image 161
SubOptimal Avatar answered Sep 24 '22 08:09

SubOptimal