简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM