论坛首页 Java版 企业应用

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

浏览 3921 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
最后更新时间:2006-09-11
恰好看到关于log的讨论。想起以前调查的一个问题。整理出来,希望对大家能有所帮助。

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 <init>
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方法。
[code:1]
// Private method to infer the caller's class and method names
private void inferCaller() {
needToInferCaller = false;
// Get the stack trace.
StackTraceElement stack[] = (new Throwable()).getStackTrace();
// First, search back to a method in the Logger class.
int ix = 0;
while (ix < stack.length) {
StackTraceElement frame = stack[ix];
String cname = frame.getClassName();
if (cname.equals("java.util.logging.Logger")) {
break;
}
ix++;
}
// Now search for the first frame before the "Logger" class.
while (ix < stack.length) {
StackTraceElement frame = stack[ix];
String cname = frame.getClassName();
if (!cname.equals("java.util.logging.Logger")) {
// We've found the relevant frame.
setSourceClassName(cname);
setSourceMethodName(frame.getMethodName());
return;
}
ix++;
}
// We haven't found a suitable frame, so just punt. This is
// OK as we are only commited to making a "best effort" here.
}
[/code:1]

Log4j有异曲同工之妙。
org.apache.log4j.spi.LocationInfo类。
先用Throwable.printStackTrace()方法把Exception信息打印到一个字符串里。
然后按行分析这个字符串。抽出调用类和方法。参见LocationInfo类的构造函数。

[code:1]
/**
Instantiate location information based on a Throwable. We
expect the Throwable <code>t</code>, to be in the format

<pre>
java.lang.Throwable
...
at org.apache.log4j.PatternLayout.format(PatternLayout.java:413)
at org.apache.log4j.FileAppender.doAppend(FileAppender.java:183)
at org.apache.log4j.Category.callAppenders(Category.java:131)
at org.apache.log4j.Category.log(Category.java:512)
at callers.fully.qualified.className.methodName(FileName.java:74)
...
</pre>

<p>However, we can also deal with JIT compilers that "lose" the
location information, especially between the parentheses.

*/
public LocationInfo(Throwable t, String fqnOfCallingClass)
[/code:1]

e.printStackTrace()把Exception发生当时的整个运行栈结构展开,打印出来。
Log4J就是分析这个打印结果,获得所有的调用层次。

关于直接获取调用类名的方法。
我们来看sun.reflect.Reflection的getCallerClass()方法的说明。

[code:1]
/** Returns the class of the method <code>realFramesToSkip</code>
frames up the stack (zero-based), ignoring frames associated
with java.lang.reflect.Method.invoke() and its implementation.
The first frame is that associated with this method, so
<code>getCallerClass(0)</code> returns the Class object for
sun.reflect.Reflection. Frames associated with
java.lang.reflect.Method.invoke() and its implementation are
completely ignored and do not count toward the number of "real"
frames skipped. */
public static native Class getCallerClass(int realFramesToSkip);
[/code:1]

这是一个native方法。原理也是根据StackFrame(运行栈)获取相应类的信息。这个方法直接返回一个Class名字,直接有效。参数realFramesToSkip用来选取你所需要的Stack层次,所以,你可以用这个方法获得任何层次的上的调用类名。

Throwable.getStackTrace()也是一个native方法。原理也是根据StackFrame(运行栈)获取相应类的信息。返回一个StackTraceElement[]。
StackTraceElement类在JDK1.4的java.lang的包里面。里面包含丰富的信息,非常适合Debug。
StackTraceElement类有如下方法:
getFileName(),getLineNumber(), getClassName(), getMethodName()。
   
最后更新时间:2004-07-27
非常好:)
   
0 请登录后投票
最后更新时间:2004-07-27
以前作unit test时,我也写过一个类似,主要就是getTrueMethod() 这个方法,其中还包括jdk1.3的方法
可以直接使用。只要在类初始化时MethodTrace methodTrace = new MethodTrace();,然后在方法中methodTrace.getTrueMethod()
[code:1]/*
* Created on Feb 27, 2003 12&#58;00&#58;04 PM
*
*/
package com.bba96.util;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
* @author Leon
*/
public class MethodTrace &#123;
    // for jdk 1.4
    private StackTraceElement elements&#91;&#93; ;
   
    StringWriter sw = new StringWriter&#40;&#41;;
    PrintWriter out = new PrintWriter&#40;sw&#41;;
    private String trueMethodName = null;
    private String methodName = null;
    private String methodNameExTest = null;
    private String e = null;
    private int a&#91;&#93; = new int&#91;2&#93;;
    private int b;
    private String cutStr = &quot;test&quot;;
    private int cutLength = cutStr.length&#40;&#41;;
    private char&#91;&#93; line = null;
    private StringBuffer buf = new StringBuffer&#40;&#41;;
    public MethodTrace&#40;&#41; &#123;
    &#125;
    private String cutTestStr&#40;String str&#41; &#123;
        if &#40;str == null&#41; &#123;
            return null;
        &#125;
        String strLowerCase = str.toLowerCase&#40;&#41;;
        int i = strLowerCase.indexOf&#40;cutStr&#41;;
        int j;
        if &#40;i != -1&#41; &#123;
            line = str.toCharArray&#40;&#41;;
            buf.setLength&#40;str.length&#40;&#41;&#41;;
            buf.append&#40;line, 0, i&#41;;
            i += cutLength;
            j = i;
            i = strLowerCase.indexOf&#40;cutStr, i&#41;;
            while &#40;i != -1&#41; &#123;
                buf.append&#40;line, j, i - j&#41;;
                i += cutLength;
                j = i;
                i = strLowerCase.indexOf&#40;cutStr, i&#41;;
            &#125;
            buf.append&#40;line, j, line.length - j&#41;;
            str = buf.toString&#40;&#41;;
            buf.setLength&#40;0&#41;;
        &#125;
        return str;
    &#125;
    public String getTrueMethod&#40;&#41; &#123;
        trueMethodName = null;
        try &#123;
            b = a&#91;4&#93;;
        &#125; catch &#40;ArrayIndexOutOfBoundsException aioobe&#41; &#123;
            // jdk 1.3
            /*
            aioobe.printStackTrace&#40;out&#41;;
            out.flush&#40;&#41;;
            e = sw.toString&#40;&#41;;
            try &#123;
                out.close&#40;&#41;;
                sw.close&#40;&#41;;
            &#125; catch &#40;IOException e&#41; &#123;
                // Do nothing, this should not happen as it is StringWriter.
            &#125;
            out = null;
            sw = null;
            boolean logError = false;
            int pos = e.indexOf&#40;&quot;at &quot;&#41;;
            for &#40;int i = 0; i &lt; 3; i++&#41; &#123;
                if &#40;pos == -1&#41; &#123;
                    logError = true;
                    break;
                &#125;
                e = e.substring&#40;pos + 3, e.length&#40;&#41;&#41;;
                pos = e.indexOf&#40;&quot;at &quot;&#41;;
            &#125;
            if &#40;logError&#41; &#123;
                trueMethodName = &quot;UnknownClass.unknownMethod&#40;&#41;&quot;;
            &#125; else &#123;
                trueMethodName = e.substring&#40;0, e.indexOf&#40;'&#40;'&#41;&#41;;
            &#125;
            */
           
            // for jdk 1.4
           
            elements = aioobe.getStackTrace&#40;&#41;;
            if &#40;elements.length &lt; 3&#41; &#123;
            return &quot;UnknownClass.unknownMethod&#40;&#41;&quot;;
            &#125;
            trueMethodName = elements&#91;2&#93;.getClassName&#40;&#41; + &quot;.&quot; + elements&#91;2&#93;.getMethodName&#40;&#41;;
           
        &#125;
        return trueMethodName;
    &#125;
    public String getMethod&#40;&#41; &#123;
        return methodName;
    &#125;
    public String getMethodExTest&#40;&#41; &#123;
        methodNameExTest = cutTestStr&#40;getTrueMethod&#40;&#41;&#41;;
        int index = methodNameExTest.lastIndexOf&#40;'.'&#41;;
        methodNameExTest =
            methodNameExTest.substring&#40;0, index + 1&#41;
                + methodNameExTest.substring&#40;index + 1, index + 2&#41;.toLowerCase&#40;&#41;
                + methodNameExTest.substring&#40;index + 2, methodNameExTest.length&#40;&#41;&#41;;
        return methodNameExTest;
    &#125;
&#125;[/code:1]
   
0 请登录后投票
最后更新时间:2004-07-27
lllyq 写道
以前作unit test时,我也写过一个类似,主要就是getTrueMethod() 这个方法,其中还包括jdk1.3的方法
可以直接使用。只要在类初始化时MethodTrace methodTrace = new MethodTrace();,然后在方法中methodTrace.getTrueMethod()


非常棒的代码。
for jdk1.3 的部分,和log4j的思路一样。在这方面,你和log4j大师有一比。
for jdk1.4 的部分也和JDK 1.4 Log的实现方法一样。

我以前怎么也不明白log4j是如何实现的。只有看了源代码才明白。
JDK1.4后来为了支持log才加入了StackTraceElement。
JDK1.3的时候,确实只能用分析Throwable StackTrace字符串这个方法实现。
   
0 请登录后投票
论坛首页 Java版 企业应用

跳转论坛:
JavaEye推荐