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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With