Amirio
Amirio

Reputation: 788

how to filter specific class logger in logback.xml?

we try to filter logs generated from one class:

com.websudos.phantom

for two goals:

  1. all logs from app saved in the file except log from this calss

  2. all log from this file transferred to graylog.

we have filter those log by regex with this filter:

<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
    <evaluator>
        <matcher>
        <Name>parameter</Name>
        <regex>Executing query</regex>
    </matcher>
    <expression>parameter.matches(formattedMessage)</expression>
    </evaluator>
    <OnMismatch>DENY</OnMismatch>
    <OnMatch>ACCEPT</OnMatch>
</filter>

the Executing query regex for this class : com.websudos.phantom

and we do not accept to set a level of this class to OFF because we need this log to transfer to graylog and not saving in the file!

whats a solution?

Upvotes: 8

Views: 17152

Answers (2)

Ariel
Ariel

Reputation: 26753

XML:

<filter class="com.websudos.loggers.ClassNameFilter">
    <className>com.websudos.phantom</className>
    <onMatch>ACCEPT</onMatch>
</filter>

Java:

package com.websudos.loggers;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.filter.AbstractMatcherFilter;
import ch.qos.logback.core.spi.FilterReply;

public class ClassNameFilter extends AbstractMatcherFilter<ILoggingEvent> {

    String loggerName;

    @Override
    public FilterReply decide(ILoggingEvent event) {
        if (!isStarted()) {
            return FilterReply.NEUTRAL;
        }

        if (event.getLoggerName().equals(loggerName)) {
            return onMatch;
        } else {
            return onMismatch;
        }
    }

    public void setClassName(String className) {
        this.loggerName = className;
    }

    @Override
    public void start() {
        if (this.loggerName != null) {
            super.start();
        }
    }
}

You can easily enough modify this to check logging level as well. See ch.qos.logback.classic.filter.LevelFilter for an example.

Upvotes: 5

Amirio
Amirio

Reputation: 788

this is a solution:

<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
  <evaluator> <!-- defaults to type ch.qos.logback.classic.boolex.JaninoEventEvaluator -->
    <expression>logger.equals("com.websudos.phantom")</expression>
  </evaluator>
  <OnMismatch>NEUTRAL</OnMismatch>
  <OnMatch>DENY</OnMatch>
</filter>

by add this filter to any appander, logs from class com.websudos.phantom ignored

Upvotes: 8

Related Questions