how to filter specific class logger in logback.xml?
Asked Answered
A

2

8

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?

Aeniah answered 14/7, 2018 at 6:14 Comment(0)
A
8

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

Aeniah answered 14/7, 2018 at 6:51 Comment(1)
Just one note - don't forget to add janino to your maven dependencies.Camlet
S
5

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.

Sliding answered 13/12, 2019 at 8:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.