package org.xbib.logging.filters;

import java.text.MessageFormat;
import java.util.logging.Filter;
import java.util.logging.LogRecord;
import java.util.regex.Pattern;
import org.xbib.logging.ExtLogRecord;

/**
 * A regular-expression-based filter. Used to exclude log records which match or don't match the expression. The
 * regular expression is checked against the raw (unformatted) message.
 */
public final class RegexFilter implements Filter {

    private final Pattern pattern;

    /**
     * Create a new instance.
     *
     * @param pattern the pattern to match
     */
    public RegexFilter(final Pattern pattern) {
        this.pattern = pattern;
    }

    /**
     * Create a new instance.
     *
     * @param patternString the pattern string to match
     */
    public RegexFilter(final String patternString) {
        this(Pattern.compile(patternString));
    }

    /**
     * Determine if this log record is loggable.
     *
     * @param record the log record
     * @return {@code true} if the log record is loggable
     */
    @Override
    public boolean isLoggable(final LogRecord record) {
        final String msg;
        if (record instanceof ExtLogRecord) {
            msg = ((ExtLogRecord) record).getFormattedMessage();
        } else {
            msg = MessageFormat.format(record.getMessage(), record.getParameters());
        }
        return pattern.matcher(String.valueOf(msg)).find();
    }
}
