豆沙包

…… …… 所学 所写 所想 所做 所悟…… ……

如何获取call stack(调用栈)信息——之一

         我们中的大多数人每天都会面对logging API,JDK1.4中的Logger, Log4j等,从他们生成的log文件中,我们可以知道日志产生的第一现场信息,比如源文件名,全限定类名,当前方法名,以及记录日志是源代码中第几行等,那有没有考虑过这些信息是如何获取的呢?
         
         我们先来看一段代码
…………
…………
void doSomething(){
     logger.info(
"doSomething()调用成功");
}

…………
…………
这是我最常见的日志记录方式。

      我下面就开始我们的追踪以查出logging API是如何记录上面提到的这些metadata的。

      这儿以JDK1.4中的logging API为研究对象。

      先进入java.util.logging.Logger中,看一下info(String msg)这个方法
    public void info(String msg) {
    
if (Level.INFO.intValue() < levelValue) {
        
return;
    }

    log(Level.INFO, msg);
    }
      继续追踪
    public void log(Level level, String msg) {
    
if (level.intValue() < levelValue || levelValue == offValue) {
        
return;
    }

    LogRecord lr 
= new LogRecord(level, msg);
    doLog(lr);
    }

这儿我们发现了一个值得关注的类 LogRecord ,从名字上猜应该是和日志信息有关的一个类。我们来看一下它的Javadoc中的描述
/**
 * LogRecord objects are used to pass logging requests between
 * the logging framework and individual log Handlers.
 * <p>
 * When a LogRecord is passed into the logging framework it 
 * logically belongs to the framework and should no longer be
 * used or updated by the client application.
 * <p>
 * Note that if the client application has not specified an
 * explicit source method name and source class name, then the
 * LogRecord class will infer them automatically when they are
 * first accessed (due to a call on getSourceMethodName or
 * getSourceClassName) by analyzing the call stack.  
   
        从这儿可以看到:注意如果客户端程序没有显式地指定源方法名和源类名,则LogRecord 类将通过分析 call stack(调用栈)来自动提取这些信息(方法getSourceMethodname和方法getSourceClassName),我们已经走在正确的道路上了,继续追查getSourceMethodname()…………
         
    (未完)

posted on 2005-03-13 17:58 carob 阅读(1626) 评论(0)  编辑  收藏 所属分类: Reflection


只有注册用户登录后才能发表评论。


网站导航: