Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

google protocol buffers pretty print

For logging purposes I need to write the content of a google protocol buffer message to the log output (java). Haven't found a way to do this yet.

I found TextFormat but TextFormat expects an instance of MessageOrBuilder. The Message I currently need to print out doesn't extend MessageOrBuilder, it extends GeneratedMessageLite and implements MessageLiteOrBuilder.

Any idea how I can get a pretty or at least human readable string representation out of this message?

like image 727
peez80 Avatar asked Dec 15 '25 02:12

peez80


1 Answers

It sounds like you are using Protobuf in "lite mode", i.e. your .proto file contains option optimize_for = LITE_RUNTIME;. Lite mode removes all introspection facilities of Protocol Buffers, and TextFormat depends on those introspection capabilities. So, if you want to be able to use .toString() (and get a useful result), you will need to change back from Lite mode to regular mode.

This means that the library will be bigger and slower to start up. Unfortunately there's really no way around this. If you want introspection/stringification, this is the cost.

Some other options you might consider, though:

  • If this is for debugging purposes, you might use lite mode for "release" builds and use regular mode only for debug builds.
  • For production logging, it may make sense to write the logs in raw protobuf format, and decode them later, e.g. using protoc --decode or a tool you write yourself.
like image 184
Kenton Varda Avatar answered Dec 16 '25 14:12

Kenton Varda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!