Lo que haremos será "engañar" a la aplicación dándole un proxy en lugar del objeto real y dicho proxy se encargará de hacer el logging y de delegar en el objeto real la lógica de negocio.
Utilizarlo es realmente simple:
public class LoggingHandler implements InvocationHandler {
private final Logger LOG;
private Object delegate;
public LoggingHandler(Object delegate) {
this.delegate = delegate;
this.LOG = Logger.getLogger(delegate.getClass());
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
LOG.debug(">>" + method.getName());
Object result = method.invoke(delegate, args);
return result;
} catch (InvocationTargetException e) {
throw e.getTargetException();
} finally {
LOG.debug("<<" + method.getName());
}
}
}
Se da por supuesto que como buenos programadores estáis programando usando interfaces en caso contrario no podréis "dar el cambiazo".
Test t = new TestImpl();
InvocationHandler handler = new LoggingHandler(t);
Test proxy = (Test) Proxy.newProxyInstance(
t.getClass().getClassLoader(),
t.getClass().getInterfaces(),
handler);
proxy.echo("hello world");



asu me falta conocer más de sistemas.
ResponderSuprimir