Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing spring bean from logging appender class

Tags:

spring

log4j

I have log4j DailyRollingFileAppender class in which setFile() method I need to check database value to decide which file to used for logging.

DailyRollingFileAppender class 

public void setFileName()
{
    isLoginEnabled = authenticationManager.checkLoginLogging();
}

Here 'authenticationManager' is object of class used to make database call using spring dependency injection feature.

spring-beans.xml
<bean id="dailyRollingFileAppender" class="com.common.util.DailyRollingFileAppender">
 <property name="authenticationManager">
     <ref bean="authenticationManager"/>
 </property>
</bean>

<bean id="authenticationManager" class="com.security.impl.AuthenticationManagerImpl">
    <property name="userService">
        <ref bean="userService"/>
</property>
</bean>

Now when I start my application log4j gets initiated first and since spring-beans is yet to invoked it throws NullPointerException in method setFileName(). So is there a way I can make call to 'authenticationManager.checkLoginLogging();' from DailyFileAppender class so that when log4j loads it should able to get database value?

like image 576
swapnil chorghe Avatar asked Sep 05 '12 05:09

swapnil chorghe


1 Answers

A few years late, but I hope this is of help to someone.

I was after similar functionality - I have a custom appender, and i wanted to use an autowired bean to perform some logging using a service we'd built. By making the appender implement the ApplicationContextAware interface, and making the field that i'd normally autowire static, i'm able to inject the spring-controlled bean into the instance of the appender that log4j has instantiated.

@Component
public class SslErrorSecurityAppender extends AppenderSkeleton implements ApplicationContextAware {

    private static SecurityLogger securityLogger;

    @Override
    protected void append(LoggingEvent event) {
        securityLogger.log(new SslExceptionSecurityEvent(SecurityEventType.AUTHENTICATION_FAILED, event.getThrowableInformation().getThrowable(), "Unexpected SSL error"));
    }

    @Override
    public boolean requiresLayout() {
        return false;
    }

    @Override
    public synchronized void close() {
        this.closed = true;
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        if (applicationContext.getAutowireCapableBeanFactory().getBean("securityLogger") != null) {
            securityLogger = (SecurityLogger) applicationContext.getAutowireCapableBeanFactory().getBean("securityLogger");
        }
    }
}
like image 124
bertybro Avatar answered Oct 26 '22 19:10

bertybro