Bart van Heukelom
Bart van Heukelom

Reputation: 44094

Different appender types for Logback Sifting Appender

I've configured a SiftingAppender like this:

<appender name="FILE" class="ch.qos.logback.classic.sift.SiftingAppender">

    <discriminator>
        <key>context</key>
        <defaultValue>global</defaultValue>
    </discriminator>

    <!-- sift into different files -->
    <sift>
        <appender name="FILE-${context}" class="ch.qos.logback.core.FileAppender">
            <file>${logroot}/${context}.log</file>
            <encoder>
                <pattern>[%d{HH:mm:ss.SSS}] %-5level %logger{36} [%thread]%n%msg%n</pattern>
            </encoder>
        </appender>
    </sift>

</appender>

Now, I would like to have a RollingFileAppender in there, but only for the messages without context. Those with context are generally not very large, but the global one is.

Is this possible?

Upvotes: 2

Views: 4780

Answers (3)

Keith Garry Boyce
Keith Garry Boyce

Reputation: 1

You can use a filter on the appenders. The filter on your appender will include and the filter on the other appenders will exclude

Upvotes: 0

Wesley Womack
Wesley Womack

Reputation: 343

I think the best thing in this situation is to extend the SiftingAppender and override append and throw out anything that does not have the key (instead of using the default).

The quickest way I can think of is to create two appenders and have the events sent to both. Then configure the SiftingWhileRejectingDefaultAppender to use the RollingFileAppender and configure the SiftingRejectAllButDefaultAppender to use the regular FileAppender.

SiftingWhileRejectingDefaultAppender

import ch.qos.logback.classic.sift.SiftingAppender;
import ch.qos.logback.classic.spi.ILoggingEvent;

public class SiftingWhileRejectingDefaultAppender extends SiftingAppender {

    @Override
    protected void append(ILoggingEvent event) {
        String discriminatingValue = this.getDiscriminator().getDiscriminatingValue(event);
        if (!discriminatingValue.equals("global")) {
            super.append(event);
        }
    }
}

SiftingRejectAllButDefaultAppender

import ch.qos.logback.classic.sift.SiftingAppender;
import ch.qos.logback.classic.spi.ILoggingEvent;

public class SiftingRejectAllButDefaultAppender extends SiftingAppender {

    @Override
    protected void append(ILoggingEvent event) {
        String discriminatingValue = this.getDiscriminator().getDiscriminatingValue(event);
        if (discriminatingValue.equals("global")) {
            super.append(event);
        }
    }
}

Upvotes: 5

lorthos
lorthos

Reputation: 427

i think you can do this with the groovy configuration if it is an option for you. You can write the if statement based on the discriminator

appender("SIFT", GSiftingAppender) {
 discriminator(MDCBasedDiscriminator) {
      key = "context"
      defaultValue = "global"
 }
 sift {
  if(..) {
         appender(....) {
         }
  }
 }
}

Upvotes: 3

Related Questions