c++protocol-buffers

Omit fields when printing Protobuf message


Is it possible to choose what fields or at least what field types to be considered when calling message.DebugString() in Google Protobuf?

I have the following message description:

message Message
{
    optional string name = 1
    optional int32 blockSize = 2;
    optional bytes block = 3;
}

I only want to print name and blockSize and omit the block field, which happens to be large (e.g.: 64KB) and its content is insignificant.

I built a method that specifically adds to a std::stringstream only the fields of interest but it seems that I have to modify the method for every change in message description.


Solution

  • Your best bet is to make a copy of the message, clear block from the copy, then print it.

    Message copy = original;
    copy.clear_block();
    cout << copy.DebugString() << endl;
    

    Note that there's no performance concern here because DebugString() itself is already much slower than making a copy of the message.

    If you want to make this more general, you could write some code based on protobuf reflection which walks over the copied message and removes all fields of type bytes with long sizes.