Ведение журнала AOP: @Aspect не регистрирует ошибку в консоли для конфигурации по умолчанию log4j - PullRequest
1 голос
/ 24 марта 2019

Я новичок в Spring и пытаюсь реализовать Spring AOP, используя log4j для регистрации ошибок в консоли.Обратите внимание, что у меня нет log4j.xml в моем проекте, но это должно быть хорошо, так как я просто хочу регистрировать ошибку в консоли, используя концепцию Spring AOP.

Ниже приведен мой код и когда я его запускаюЯ вижу трассировку стека исключений в консоли, но не вижу, что мой LoggingAspect.java регистрирует ошибку в консоли, как и должно быть.

Я попытался добавить статический блок в LoggingAspect.Java для печати некоторого текста в консоли с помощью System.out.println (), но он не печатает.

SpringConfig.java

package exercise5.com.aadi.configuration;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages = "exercise5.com.aadi.service")
public class SpringConfig {
}

LoggingAspect.java

package exercise5.com.aadi.utility;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;


@Aspect
@Component
public class LoggingAspect {

    @AfterThrowing(pointcut = "execution(* exercise5.com.aadi.service.*Impl.*(..))", throwing = "exception")
    public void logExceptionFromService(Exception exception) throws Exception {
        Logger logger = LogManager.getLogger(this.getClass());
        logger.error(exception);
    }
}

Мое исключение исходит от DAO

InsuranceServiceImpl.java

package exercise5.com.aadi.service;

...
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

...

@Service(value = "insuranceService")
public class InsuranceServiceImpl implements InsuranceService {

    ...

    @Override
    public List<PolicyReport> getReport(String policyType) throws Exception {
        ...

        if (filteredPolicy.isEmpty())
            throw new Exception("Service.NO_RECORD");

        ...

    }

    ...
}

Ниже приведено консольное сообщение, которое я получаю

ERROR StatusLogger No Log4j 2 configuration file found. Using default configuration (logging only errors to the console), or user programmatically provided configurations. Set system property 'log4j2.debug' to show Log4j 2 internal initialization logging. See https://logging.apache.org/log4j/2.x/manual/configuration.html for instructions on how to configure Log4j 2
Exception in thread "main" java.lang.Exception: Service.NO_RECORD
    at exercise5.com.aadi.service.InsuranceServiceImpl.getReport(InsuranceServiceImpl.java:43)
    at exercise5.com.aadi.ui.UserInterface.generateReport(UserInterface.java:45)
    at exercise5.com.aadi.ui.UserInterface.main(UserInterface.java:20)

Но то, что я ожидаюis

ERROR StatusLogger No Log4j 2 configuration file found. Using default configuration (logging only errors to the console), or user programmatically provided configurations. Set system property 'log4j2.debug' to show Log4j 2 internal initialization logging. See https://logging.apache.org/log4j/2.x/manual/configuration.html for instructions on how to configure Log4j 2
Exception in thread "main" 02:03:52.656 [main] ERROR exercise5.com.aadi.service.InsuranceServiceImpl
java.lang.Exception: Service.NO_RECORD
    at exercise5.com.aadi.service.InsuranceServiceImpl.getReport(InsuranceServiceImpl.java:56) [bin/:?]
    at exercise5.com.aadi.ui.UserInterface.generateReport(UserInterface.java:45) [bin/:?]
    at exercise5.com.aadi.ui.UserInterface.main(UserInterface.java:20) [bin/:?]
java.lang.Exception: Service.NO_RECORD
    at exercise5.com.aadi.service.InsuranceServiceImpl.getReport(InsuranceServiceImpl.java:56)
    at exercise5.com.aadi.ui.UserInterface.generateReport(UserInterface.java:45)
    at exercise5.com.aadi.ui.UserInterface.main(UserInterface.java:20)

Обратите внимание, что два раза должен присутствовать журнал исключений.Первый из Spring AOP LoggingAspect.java, а второй - обычная трассировка стека исключений.

Кто-нибудь может мне помочь, почему я не получаю первый?

1 Ответ

0 голосов
/ 25 марта 2019

Вы указываете

@ComponentScan(basePackages = "exercise5.com.aadi.service")

Что означает, что ваш LoggingAspect @Component не будет поднят Spring, потому что он живет под

exercise5.com.aadi.utility

Кроме того, ваша конфигурация AOP, кажется, на точке.

...