豆沙包

          …… …… 所學 所寫 所想 所做 所悟…… ……

          如何獲取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 閱讀(1654) 評論(0)  編輯  收藏 所屬分類: Reflection

          主站蜘蛛池模板: 彭山县| 长宁区| 青海省| 安泽县| 关岭| 新野县| 定襄县| 莱西市| 惠东县| 佛山市| 桑植县| 四会市| 山东省| 洛阳市| 三台县| 东阳市| 桦甸市| 鸡泽县| 周至县| 河源市| 定兴县| 岚皋县| 宜黄县| 应用必备| 资源县| 西乌珠穆沁旗| 亳州市| 陆川县| 灵石县| 栖霞市| 金秀| 蒙阴县| 前郭尔| 萝北县| 阳春市| 英吉沙县| 光泽县| 南召县| 宁都县| 平原县| 瑞金市|