Instead of trying to get developers to remember to log each service method call and/or exception, is there a pattern that will proxy to t开发者_如何学Gohe right service method, in the process logging the call, and trapping/logging any exceptions that are thrown before returning a response back to the caller? I know there is a proxy pattern, but I'm not sure it does what I need it to... if there is a way to create an interface that will better enforce a logging requirement, then I'm open to that as well.
Logging is a cross cutting concern. You can use AOP for that. Have a look at AspectJ
or Spring AOP
.
You could consider using Dynamic proxies for implementing your service layer.
It uses the reflection api so all method calls to your service code will go through a single "invoke" method where you can log service calls, method parameters and exception messages.
public class MyServiceProxy implements InvocationHandler {
public static Object newInstance(Object obj) {
return java.lang.reflect.Proxy.newProxyInstance(
obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(),
new MyServiceProxy(obj));
}
public Object invoke(Object proxy, Method m, Object[] args) {
// Log method name , parameters etc.
try {
method.invoke(proxy, args) ;
}
catch(InvocationTargetException e) {
// log your exceptions and do other things
throw e.getTargetException();
}
}
Where you call your service, you would instead do this
MyService myServiceRef = (MyService)MyServiceProxy.newInstance(new MyService());
精彩评论