Java – use logback to mask passwords?
At present, we usually record all XML documents in and out of the system, some of which contain explicit passwords We want to be able to configure the logback logger / appender that performs this operation to perform some pattern matching or similar operations. If it detects that there is a password to replace it (most likely an asterisk) Note that we don't want to filter out log entries, we want to block part of it I appreciate the advice on how to use logback to do this thank you.
Solution
Logback version 0.9 27 introduces replacement capability Substitution supports regular expressions For example, if the recorded message is "userid = Alice, pswd = 'my secret", the output mode is
"%d [%t] $logger - %msg%n",
You just need to change the mode to
"%d [%t] $logger - %replace(%msg){"pswd='.*'","pswd='xxx'"}%n"
Note that option quoting is used above
The previous log message will be output as "userid = Alice, pswd = 'xxx'"
For superior performance, you can also mark log statements as reliable and instruct% replace to perform replacement only for log statements marked as reliable For example,
Marker confidential = MarkerFactory.getMarker("CONFIDENTIAL"); logger.info(confidential,"userid={},password='{}'",userid,password);
Unfortunately, the current version of logback does not support conditional substitution (tag based or other) However, you can easily write your own replacement code by extending the replacing composite converter If you need further help, please shout on the logback user mailing list