在测试《Spring从入门到精通》使用Java的代理机制进行日志输出 这段代码时我的并没有输出日志信息,找了好多博客都没有解决,记录一下
package proxy; import org.apache.log4j.Level; import org.apache.log4j.Logger; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class LogProxy implements InvocationHandler{ private Logger logger=Logger.getLogger(this.getClass().getName()); private Object delegate; //绑定代理对象 public Object bind(Object delegate){ this.delegate=delegate; return Proxy.newProxyInstance(delegate.getClass().getClassLoader(),delegate.getClass().getInterfaces(),this); } //针对接口编程 public Object invoke(Object proxy,Method method, Object[] args) throws InvocationTargetException, IllegalAccessException { Object result=null; logger.log(Level.INFO,args[0]+"开始审核数据"); try { result=method.invoke(delegate,args); logger.log(Level.INFO,args[0]+"审核结束"); }catch(Exception e){ logger.log(Level.INFO,e.toString()); } return result; } } interface TimeBookInterface{ public void doAuditing(String name); } class TimeBook implements TimeBookInterface{ public void doAuditing(String name){ System.out.println("业务逻辑"); } } class test{ public static void main(String args[]){ LogProxy logProxy=new LogProxy(); TimeBookInterface timeBookInterface = (TimeBookInterface)logProxy.bind(new TimeBook()); timeBookInterface.doAuditing("张三"); } }
输出信息:
业务逻辑 log4j:WARN No appenders could be found for logger (proxy.LogProxy). log4j:WARN Please initialize the log4j system properly. log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.