Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I automatically log use of any @Deprecated annoted method in Java?

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 ?

like image 636
temsa Avatar asked Mar 04 '10 16:03

temsa


2 Answers

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.

like image 176
Daff Avatar answered Oct 11 '22 04:10

Daff


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.

like image 36
Adrian Avatar answered Oct 11 '22 03:10

Adrian