Pass application.properties to Logback Custom Filter

parrotjack :

I use spring boot, i want to get application.properties attribute in custom filter of logback. I know how to get it in normally but this is quite different case for me.

my application.properties,

sample.name="firstName"

and logback-spring.xml contains,

<configuration>

    <property resource="application.properties" />

    <springProperty scope="context" name="firstName" source="sample.name"/>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">

        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>${logging.console.level:-ERROR}</level>
        </filter>
        <encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
            <layout class="com.xxx.xxx.logback.LogbackJsonEventLayout"/>
        </encoder>
        <filter class="com.xx.xx.logging.CriticalAlertLoggerFilter"/>

    </appender>

    <root level="error">
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>

Created customer filter,

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

@Component
public class CriticalAlertLoggerFilter extends Filter<ILoggingEvent> {

  public static final String ALERT_CRITICAL_STATUS = "CRITICAL";

  @Value("${firstName}")  // This is not working using @Value and not sure how to get it.
  private String name;

  @Override
  public FilterReply decide(ILoggingEvent event) {
    if (event.getLevel().isGreaterOrEqual(Level.ERROR)) {
      MDC.put("sp-eventSourceUUID",name);

    return FilterReply.ACCEPT;
  }
}

am wondering how to get the properties value of sample.name in my customer filter.

Pino :

The filter should not contain Spring annotations. Create a setter method for the name property and set its value through your logback-spring.xml as follows:

<filter class="com.mycompany.logback.filter.CriticalAlertLoggerFilter">
    <name>${firstName}</name>
</filter>

It's just like ThresholdFilter in your example (it has a setLevel() method).

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=379797&siteId=1