How can I automatically log use of any @Deprecated annoted method in Java?
annotations, java, logging
Solution
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.
Problem
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 ?