- 论坛徽章:
- 0
|
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 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 ...
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/58547/showart_469516.html |
|