Search code examples
javaspringspring-bootprotocol-buffersgrpc

How to mask out some field in grpc response when logging


I want to mask out some field when logging. is there any good way to mask out?

after message is served to client. I'm trying to mask out some field before logging

how do you mask out field?

--served to client
message {
  id : "user",
  phoneNumber : "12341234"
}


--logged response
message {
  id : "user",
  phoneNumber : "12******"
}


Solution

  • I don't think there is a way to alter the data like you mentioned, however there is a way to hide field that you don't want to print in the log (I assume its for security reasons). The way yo do that is with FieldMask.

    So for the sake of the example I took the liberty of adding another field to the schema I assume you have:

    message User {
      string id = 1;
      string name = 2;
      string phone_number = 3;
    }
    

    So now let's say that I don't want to show the phone number of my users, I can use a FieldMask to keep only id and name. So first we build a FieldMask (you'll need to add this dependency for accessing FieldMaskUtil):

    public static final FieldMask WITH_ID_AND_NAME =
                FieldMaskUtil.fromFieldNumbers(User.class,
                        User.ID_FIELD_NUMBER,
                        User.NAME_FIELD_NUMBER);
    

    then what I can do is merge this FieldMask with an existing object:

    private static void log(User user, FieldMask fieldMask) {
        User.Builder userWithMaskedFields = User.newBuilder();
        FieldMaskUtil.merge(fieldMask, user, userWithMaskedFields);
    
        System.out.println(userWithMaskedFields);
    }
    
    public static void main(String[] args) {
        User user = User.newBuilder()
            .setId("user")
            .setName("a name")
            .setPhoneNumber("12341234")
            .build();
    
        System.out.println("---Without FieldMask---");
        System.out.println(user);
        System.out.println("---With FieldMask---");
        log(user, WITH_ID_AND_NAME);
    }
    

    This will give me the following output:

    ---Without FieldMask---
    id: "user"
    name: "a name"
    phone_number: "12341234"
    
    ---With FieldMask---
    id: "user"
    name: "a name"
    

    I hope that helps, let me know if you need more details, I can update my answer.