Search code examples
javaspring-bootlog4j

Mask sensitive data via annotation using log4j


I use log4j2 in my Spring Boot project. When log event happens I want to mask sensitive data in my DTO using annotation, for example:

@Sensitive(fields = {password, email})
public class MyDTO {

   private String name;
   private String email;
   private String password

}

I want to have opportunity to set fields to mask in annotation props.

I tried to use custom serialiser for this, but I do not want to mask data every time when I serialise my DTO, only when logging event happens.

I tried to apply RewritePolicy, but in this case I already have logging message as String and I can't access class to grab annotation params to know what fields should be masked.

It would be grate to handle log event before myDto.toString() method invoked, get annotation from class, check fields to mask and replace them before set log message.

Could you please help me?


Solution

  • i am also looking like same... have extra requirement like if mobileNumber fields we have to mask first 5 characters

    As of my knowledge

    we can mask fields using log4j configuration file. https://objectpartners.com/2017/09/26/masking-sensitive-data-in-log4j-2/

    see my blog as well https://medium.com/@kspendli/logmasking-though-java-annotations-bffbd01aab1e