Mask sensitive data in logs with logback

后端 未结 6 2084
难免孤独
难免孤独 2020-11-30 04:05

I need to be able to search an event for any one of a number of patterns and replace the text in the pattern with a masked value. This is a feature in our application intend

6条回答
  •  情话喂你
    2020-11-30 04:44

    I've used censor based on RegexCensor from library https://github.com/tersesystems/terse-logback. In logback.xml

    
    
    
    
    
    

    where i put list regex replacements.

    @Getter@Setter    
    public class SensitiveDataCensor extends ContextAwareBase implements Censor, LifeCycle {
        protected volatile boolean started = false;
        protected String name;
        private List> replacementPhrases = new ArrayList<>();
    
        public void start() {
    
            String ssnJsonPattern = "\"(ssn|socialSecurityNumber)(\"\\W*:\\W*\".*?)-(.*?)\"";
            replacementPhrases.add(Pair.of(Pattern.compile(ssnJsonPattern), "\"$1$2-****\""));
    
            String ssnXmlPattern = "<(ssn|socialSecurityNumber)>(\\W*.*?)-(.*?)$2-**** replacementPhrase : replacementPhrases) {
                outcome = replacementPhrase.getLeft().matcher(outcome).replaceAll(replacementPhrase.getRight());
            } 
            return outcome;
        }
    }
    

    and used it in logback.xml like this

    [ignore] <---- IMPORTANT to disable original message field so you get only censored message
    ...
    
        {"message": "%censor(%msg){censor-sensitive}"}
    
    

提交回复
热议问题