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 ?
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 ?
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.
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
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.
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.