views:

80

answers:

4

I'm currently using slf4j on top of log4j for logging. I would like to automagically log any use of a deprecated method (annotated with the standard @Deprecated annotation) in my code.

Is there any easy way to do this ?

A: 

I think you would be sorry if you did this at runtime. Sure you could use Aspect4J to put an AOP pointcut on every method that looks for annotations; but the performance cost would be high.

danpaq
Don't know about aspect4j but with AspectJ you can just define a pointcut based on @Deprected annotation so only those methods get the advice applied, anything else is unaffected
vickirk
A: 

You can but it is going to be tough. The only solution AFAIK to "detect" method calls is by using AOP. In your case, you can write an aspect which inspects every single method call and checks if it is deprecated and logs them.

If you use spring you can start http://static.springsource.org/spring/docs/2.5.x/reference/aop.html

Please be advised that AOP has performance implications and should be used only after giving careful consideration. Perhaps you can have a flag that enables this feature in a dev/qa environment and disables them in PROD

Calm Storm
+2  A: 

If you want to log every use you will probably have to use AOP. It depends on what Frameworks you are using if there is an easy way to do this. This is how it might look like in Spring:

public class DeprecatedLoggerAdvice implements MethodInterceptor
{
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable
    {
        Methode method = invocation.getMethod();
        Annotation[] annotations = method.getAnnotations();
        boolean isDeprecated = // Check it annotations has the deprecated one in here
        if(isDeprecated)
        {
            log.warn("Called deprecated method {}", method.getName());
        }
        invocation.proceed();
    }
}

Though as already mentioned this is not good on performance. If you are using it in your application you should use that approach in combination with unit tests that cover most of your code. Then you can log and remove the use of deprecated methods and then disable AOP in production mode.

Daff
temsa
That will only be possible with compile time weaving (cglib), meaning that you will have to enable AspectJ support. I found that always to be quite a hassle but check out the documentation http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html on how it works.
Daff
+1  A: 

I can't think of an easy way to do it, but you could use the annotation processing tool to generate code that logs the use of each deprecated method.

Adrian