Search code examples
javaxmllogbackpattern-layout

Regex not working when passed as a patternproperty


The regex i am trying is to find the word next to another and replace it! When i pass this as a pattern property it doesnt seem to work.

But doesnt seem to work in the code.

I have tried this regex to check with a default java program and it seems to work fine. -> https://repl.it/repls/BlushingAccurateCarat

When i just pass in (password through the property ) it does * out passsword.

My logback.xml file

<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
    <layout class="com.vecna.nexus.facilities.loggerMasking.MaskingPatternLayout">
        <patternsProperty><![CDATA[(?<=password.{0,3})(\\w+)]]> 
        </patternsProperty>
        <pattern>%-5p %c{0} %d{dd MMM yyyy HH:mm:ss.SSS}: %m%n</pattern>
    </layout>
</encoder>

My java code

public class MaskingPatternLayout extends PatternLayout {

    private String patternsProperty;

    private Optional<Pattern> pattern;

    public String getPatternsProperty() {
        return patternsProperty;
    }

    public void setPatternsProperty(String patternsProperty) {
        this.patternsProperty = patternsProperty;
        final Logger s_log = LoggerFactory.getLogger("CHECKING STUFF");
        s_log.info(this.patternsProperty);
        if (this.patternsProperty != null) {
            this.pattern = Optional.of(Pattern.compile(patternsProperty, Pattern.MULTILINE));
        } else {
            this.pattern = Optional.empty();
        }
    }

    @Override
    public String doLayout(ILoggingEvent event) {
        final StringBuilder message = new StringBuilder(super.doLayout(event));

        if (pattern.isPresent()) {
            Matcher matcher = pattern.get().matcher(message);
            while (matcher.find()) {

                int group = 1;
                while (group <= matcher.groupCount()) {
                    if (matcher.group(group) != null) {
                        for (int i = matcher.start(group); i < matcher.end(group); i++) {
                            message.setCharAt(i, '*');
                        }
                    }
                    group++;
                }
            }
        }

        return message.toString();
    }
}

I need the output as -> password: ******** But i just get password: 12312312


Solution

  • Seems like the extra \ in (?<=password.{0,3})(\\w+) was the problem. The corrected regex that worked

    <patternsProperty><![CDATA[((?<=password.{0,3})(\w+))]]> </patternsProperty>