Search code examples
springlogback

spring inject logback TurboFilter


I use spring to inject DemoService has always been null, there is no problem with the filter inject of servlet, in the class of extends TurboFilter, how can I get the DemoService object?

https://stackoverflow.com/questions/30662641/inject-spring-bean-into-custom-logback-filter

I have tried the answer to this connection and did not solve the problem of inject.

public class ErrorLogTurboFilter extends TurboFilter {

    @Autowired
    private DemoService demoService;


    @Override
    public FilterReply decide(Marker marker, Logger logger, Level level, String s, Object[] objects, Throwable throwable) {

        // todo
         return FilterReply.NEUTRAL;
    }
}

Solution

  • Problem: Logback starts up before the Spring context. Therefore you need to lazy initialize the Filter with the to be injected bean. Apart from that the Filter will not be called as a Spring bean, but as a Turbofilter, that does not know any injections and so on.

    What you could try is define that Filter as a Spring bean in your context, that contains the DemoService. Inject the bean via a Setter for the service, but declare the field static, so you are able to access it from the logging context.

    Now during the execution you need to check if the static field is already initialized, if so you can use it without a problem.