Log信息获取调用类和调用方法名的实现原理
恰好看到关于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方法。
// Private method to infer the caller's class and method namesprivate 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.}
Log4j有异曲同工之妙。
org.apache.log4j.spi.LocationInfo类。
先用Throwable.printStackTrace()方法把Exception信息打印到一个字符串里。
然后按行分析这个字符串。抽出调用类和方法。参见LocationInfo类的构造函数。
/**Instantiate location information based on a Throwable. Weexpect 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" thelocation information, especially between the parentheses.*/public LocationInfo(Throwable t, String fqnOfCallingClass)
e.printStackTrace()把Exception发生当时的整个运行栈结构展开,打印出来。
Log4J就是分析这个打印结果,获得所有的调用层次。
关于直接获取调用类名的方法。
我们来看sun.reflect.Reflection的getCallerClass()方法的说明。
/** Returns the class of the method <code>realFramesToSkip</code>frames up the stack (zero-based), ignoring frames associatedwith 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 forsun.reflect.Reflection. Frames associated withjava.lang.reflect.Method.invoke() and its implementation arecompletely ignored and do not count toward the number of "real"frames skipped. */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()。/* * Created on Feb 27, 2003 12:00:04 PM * */package com.bba96.util;import java.io.PrintWriter;import java.io.StringWriter;/** * @author Leon */public class MethodTrace { // for jdk 1.4 private StackTraceElement elements[] ; StringWriter sw = new StringWriter();; PrintWriter out = new PrintWriter(sw);; private String trueMethodName = null; private String methodName = null; private String methodNameExTest = null; private String e = null; private int a[] = new int[2]; private int b; private String cutStr = "test"; private int cutLength = cutStr.length();; private char[] line = null; private StringBuffer buf = new StringBuffer();; public MethodTrace(); { } private String cutTestStr(String str); { if (str == null); { return null; } String strLowerCase = str.toLowerCase();; int i = strLowerCase.indexOf(cutStr);; int j; if (i != -1); { line = str.toCharArray();; buf.setLength(str.length(););; buf.append(line, 0, i);; i += cutLength; j = i; i = strLowerCase.indexOf(cutStr, i);; while (i != -1); { buf.append(line, j, i - j);; i += cutLength; j = i; i = strLowerCase.indexOf(cutStr, i);; } buf.append(line, j, line.length - j);; str = buf.toString();; buf.setLength(0);; } return str; } public String getTrueMethod(); { trueMethodName = null; try { b = a[4]; } catch (ArrayIndexOutOfBoundsException aioobe); { // jdk 1.3 /* aioobe.printStackTrace(out);; out.flush();; e = sw.toString();; try { out.close();; sw.close();; } catch (IOException e); { // Do nothing, this should not happen as it is StringWriter. } out = null; sw = null; boolean logError = false; int pos = e.indexOf("at ");; for (int i = 0; i < 3; i++); { if (pos == -1); { logError = true; break; } e = e.substring(pos + 3, e.length(););; pos = e.indexOf("at ");; } if (logError); { trueMethodName = "UnknownClass.unknownMethod();"; } else { trueMethodName = e.substring(0, e.indexOf('('););; } */ // for jdk 1.4 elements = aioobe.getStackTrace();; if (elements.length < 3); { return "UnknownClass.unknownMethod();"; } trueMethodName = elements[2].getClassName(); + "." + elements[2].getMethodName();; } return trueMethodName; } public String getMethod(); { return methodName; } public String getMethodExTest(); { methodNameExTest = cutTestStr(getTrueMethod(););; int index = methodNameExTest.lastIndexOf('.');; methodNameExTest = methodNameExTest.substring(0, index + 1); + methodNameExTest.substring(index + 1, index + 2);.toLowerCase(); + methodNameExTest.substring(index + 2, methodNameExTest.length(););; return methodNameExTest; }}/** * @author Leon * @modify liguocai */class MethodTrace { private StackTraceElement elements[] ; private int a[] = new int[2]; private int b; public MethodTrace(){ } public String getTrueMethod() { try { b = a[4]; } catch (ArrayIndexOutOfBoundsException aioobe) { // for jdk 1.4 elements = aioobe.getStackTrace(); for(StackTraceElement element : elements){ System.out.println(element.getClassName() + "\t" + element.getFileName() + "\t" + element.getLineNumber() + "\t" + element.getMethodName()); } } return elements[2].getClassName() + "." + elements[2].getMethodName() + "\t" + elements[2].getFileName() +":"+ elements[2].getLineNumber() ; } public static void main(String[] args){ new MethodTrace().mymethod(); } public void mymethod(){ log("123"); } public void log(String s){ System.out.println(new MethodTrace().getTrueMethod() + "[INFO]: " + s); }}
我精简了下您的方法,这下看清楚了,原来就是分析exception的堆栈/** * @author Leon * @modify liguocai */class MethodTrace { private StackTraceElement elements[] ; private int a[] = new int[2]; private int b; public MethodTrace(){ } public String getTrueMethod() { try { b = a[4]; } catch (ArrayIndexOutOfBoundsException aioobe) { // for jdk 1.4 elements = aioobe.getStackTrace(); for(StackTraceElement element : elements){ System.out.println(element.getClassName() + "\t" + element.getFileName() + "\t" + element.getLineNumber() + "\t" + element.getMethodName()); } } return elements[2].getClassName() + "." + elements[2].getMethodName() + "\t" + elements[2].getFileName() +":"+ elements[2].getLineNumber() ; } public static void main(String[] args){ new MethodTrace().mymethod(); } public void mymethod(){ log("123"); } public void log(String s){ System.out.println(new MethodTrace().getTrueMethod() + "[INFO]: " + s); }}
我精简了下您的方法,这下看清楚了,原来就是分析exception的堆栈
忘了贴上输出
引用testlog.MethodTraceTestLogger.java34getTrueMethod
testlog.MethodTraceTestLogger.java56log
testlog.MethodTraceTestLogger.java53mymethod
testlog.MethodTraceTestLogger.java49main
testlog.MethodTrace.mymethodTestLogger.java:53[INFO]: 123
6 楼 liguocai2009 2012-07-02 @buaawhl
老大能不能分析下多输出(输出到console,文件)的实现?
还有方法throws Exception的错误信息是怎样被拦截到的?