Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring aspectj pointcut on logging with slf4j

I'm working with spring 3.0.6. My app has lot of places where logging added (slf4j). Say I need to add some function on every serious error - it will be better for me to catch every call to error level logging and do may job after it - send mail to support with exception message, or smth like that - than manually add code to all that places in app.

I ve created following class:

@Aspect
public class LoggingWrapper {

    @Pointcut("execution (* org.slf4j.Logger.error(..))")
    public void logError() {
    }

    @AfterReturning("logError()")
    public void afterError() {
        //System.out.println("LOGERROR ASPECT AFTER");
        //send email...
    }
}

In spring config:

<aop:aspectj-autoproxy />
<bean id="loggingWrapper" class="com.app.services.LoggingWrapper"/>

Aspect is working well with my classes, but for org.slf4j.Logger - nothing happened

like image 226
crudo6 Avatar asked Mar 20 '12 08:03

crudo6


People also ask

What is PointCut in AspectJ?

AspectJ provides primitive pointcuts that capture join points at these times. These pointcuts use the dynamic types of their objects to pick out join points. They may also be used to expose the objects used for discrimination. this(Type or Id) target(Type or Id)

What is JoinPoint and PointCut?

JoinPoint: Joinpoint are points in your program execution where flow of execution got changed like Exception catching, Calling other method. PointCut: PointCut are basically those Joinpoints where you can put your advice(or call aspect). So basically PointCuts are the subset of JoinPoints.

What is aspect advice PointCut JoinPoint and advice arguments in AOP?

Aspect Oriented Programming Core Concepts Join Point: A join point is a specific point in the application such as method execution, exception handling, changing object variable values, etc. In Spring AOP a join point is always the execution of a method. Advice: Advices are actions taken for a particular join point.


1 Answers

@crudo6, this will not work with Spring @AspectJ support using proxies - the reason is the way Spring handles @AspectJ annotation is to create proxies, for eg. if you @Around advice for your @PointCut("execution (for your class)"), then Spring would create proxies for all beans in the Spring Context with types which match the class in pointcut.

Now since slf4j classes are not part of the Spring context, a proxy will not be created for them and your aspects will not take effect.

To get them to work, you can either try load time weaving or compile time weaving and use '@Pointcut("call (* org.slf4j.Logger.error(..))")' instead of execution, this way any calls to SLF4J can be intercepted by your advice. @Pointcut of execution will need weaving the slf4j libraries which may not be possible.

like image 137
Biju Kunjummen Avatar answered Sep 21 '22 07:09

Biju Kunjummen