복붙노트

[SPRING] Appender 클래스 로깅에서 Spring 빈 액세스

SPRING

Appender 클래스 로깅에서 Spring 빈 액세스

Log4J DailyRollingFileAppender 클래스에서 setFile () 메서드를 사용하여 데이터베이스 값을 검사하여 로깅에 사용할 파일을 결정해야합니다.

DailyRollingFileAppender class 

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

여기서 'authenticationManager'는 스프링 의존성 삽입 기능을 이용하여 데이터베이스 호출을하는 클래스의 객체이다.

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>

이제 응용 프로그램을 시작할 때 log4j가 먼저 시작되고 spring-beans가 아직 호출되지 않았으므로 setFileName () 메서드에서 NullPointerException을 throw합니다. 그래서 'authenticationManager.checkLoginLogging ();'을 호출 할 수있는 방법이 있습니다. DailyFileAppender 클래스에서 log4j가로드 될 때 데이터베이스 값을 가져올 수 있어야합니까?

해결법

  1. ==============================

    1.늦은 지 몇 년이지만이 사람에게 도움이되기를 바랍니다.

    늦은 지 몇 년이지만이 사람에게 도움이되기를 바랍니다.

    나는 비슷한 기능을 수행하고있었습니다. 저는 custom appender가 있습니다. autowired bean을 사용하여 우리가 만든 서비스를 사용하여 로깅을 수행하기를 원했습니다. appender가 ApplicationContextAware 인터페이스를 구현하고 일반적으로 정적으로 autowire 할 필드를 만들면 log4j가 인스턴스화 한 appender의 인스턴스에 스프링 제어 빈을 주입 할 수 있습니다.

    @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");
            }
        }
    }
    
  2. from https://stackoverflow.com/questions/12275171/accessing-spring-bean-from-logging-appender-class by cc-by-sa and MIT license