站内搜索: 请输入搜索关键词

当前页面: 开发资料首页J2SE 专题Log信息获取调用类和调用方法名的实现原理

Log信息获取调用类和调用方法名的实现原理

摘要: Log信息获取调用类和调用方法名的实现原理
<table cellSpacing=0 cellPadding=0 border=0 class="zh114" align="right"> <tr> <td > </td> </tr> </table>
  Sun JDK 源代码下载 http://wwws.sun.com/software/communitysource/
  先注册并登录到“Sun Community Source Licensing”,然后下载J2SE(几十兆)或者J2EE(几百兆)。
  
  Log能够把代码运行时间,类名,方法名,还有信息,全部都打印出来。
  一个直观的例子,每次启动Tomcat(缺省配置)的时候。一般可以看到
  Jul 9, 2004 11:22:29 AM org.apache.struts.util.PropertyMessageResources
  INFO: Initializing, config='org.apache.webapp.admin.ApplicationResources', returnNull=true
  Jul 9, 2004 11:22:41 AM org.apache.coyote.http11.Http11Protocol start
  INFO: Starting Coyote HTTP/1.1 on port 8080
  
  时间,类名,方法名,信息都打印了出来。
  那么,log是如何获取调用自身的这个类和这个方法名的呢?
  
  后面给出的代码是JDK1.4的源代码,和Log4J的源代码。说明其实现原理。
  获得调用类,和方法名,就是需要获得当前运行栈的结构。
  new Throwable().getStackTrace() 会返回当前运行栈的结构层次。
  利用这种原理,可以获得整个运行栈的调用关系。
  
  JDK1.4的java.util.logging包, 通过Throwable.getStackTrace()方法实现的。
  // Get the stack trace.
  StackTraceElement stack[] = (new Throwable()).getStackTrace();
  
  完整的代码在JDK1.4的源代码里面,java.util.logging.LogRecord类的inferCaller方法。
  
  java代码:
  2 // Private method to infer the caller's class and method names
  3 private void inferCaller() {
  ...}
  4 needToInferCaller = false;
  5 // Get the stack trace.
  6 StackTraceElement stack[] = (new Throwable()).getStackTrace();
  7 // First, search back to a method in the Logger class.
  8 int ix = 0;
  9 while (ix < stack.length) {
  ...}
  10 StackTraceElement frame = stack[ix];
  11 String cname = frame.getClassName();
  12 if (cname.equals("java.util.logging.Logger")) {
  ...}
  13 break;
  14 }
  15 ix++;
  16 }
  17 // Now search for the first frame before the "Logger" class.
  18 while (ix < stack.length) {
  ...}
  19 StackTraceElement frame = stack[ix];
  20 String cname = frame.getClassName();
  21 if (!cname.equals("java.util.logging.Logger")) {
  ...}
  22 // We've found the relevant frame.
  23 setSourceClassName(cname);
  24 setSourceMethodName(frame.getMethodName());
  25 return;
  26 }
  27 ix++;
  28 }
  29 // We haven't found a suitable frame, so just punt. This is
  30 // OK as we are only commited to making a "best effort" here.
  31 }
  32
  
  Log4j有异曲同工之妙。
  org.apache.log4j.spi.LocationInfo类。
  先用Throwable.printStackTrace()方法把Exception信息打印到一个字符串里。
  然后按行分析这个字符串。抽出调用类和方法。参见LocationInfo类的构造函数。
  
  java代码:
  1
  2 /**
  3 Instantiate location information based on a Throwable. We
  4 expect the Throwable t, to be in the format
  5
  6 

  7 java.lang.Throwable
  8 ...
  9 at org.apache.log4j.PatternLayout.format(PatternLayout.java:413)
  10 at org.apache.log4j.FileAppender.doAppend(FileAppender.java:183)
  11 at org.apache.log4j.Category.callAppenders(Category.java:131)
  12 at org.apache.log4j.Category.log(Category.java:512)
  13 at callers.fully.qualified.className.methodName(FileName.java:74)
  14 ...
  15

  16
  17

However, we can also deal with JIT compilers that "lose" the
  18 location information, especially between the parentheses.
  19
  20 */
  21 public LocationInfo(Throwable t, String fqnOfCallingClass)
  22
  
  e.printStackTrace()把Exception发生当时的整个运行栈结构展开,打印出来。
  Log4J就是分析这个打印结果,获得所有的调用层次。
  
  关于直接获取调用类名的方法。
  我们来看sun.reflect.Reflection的getCallerClass()方法的说明。
  
  java代码:
  1
  2 /** Returns the class of the method realFramesToSkip
  3 frames up the stack (zero-based), ignoring frames associated
  4 with java.lang.reflect.Method.invoke() and its implementation.
  5 The first frame is that associated with this method, so
  6 getCallerClass(0) returns the Class object for
  7 sun.reflect.Reflection. Frames associated with
  8 java.lang.reflect.Method.invoke() and its implementation are
  9 completely ignored and do not count toward the number of "real"
  10 frames skipped. */
  11 public static native Class getCallerClass(int realFramesToSkip);
  
  这是一个native方法。原理也是根据StackFrame(运行栈)获取相应类的信息。这个方法直接返回一个Class名字,直接有效。参数realFramesToSkip用来选取你所需要的Stack层次,所以,你可以用这个方法获得任何层次的上的调用类名。
  
  Throwable.getStackTrace()也是一个native方法。原理也是根据StackFrame(运行栈)获取相应类的信息。返回一个StackTraceElement[]。
  StackTraceElement类在JDK1.4的java.lang的包里面。里面包含丰富的信息,非常适合Debug。
  StackTraceElement类有如下方法:
  getFileName(),getLineNumber(), getClassName(), getMethodName()。
  


<table width="96%"> <tr> <td background="http:///images/dian.gif" height="3"></td> </tr> </table>

↑返回目录
前一篇: 应用Java技术实现数据库应用系统
后一篇: 我来说说Bean的使用方法