豆沙包

          …… …… 所學(xué) 所寫 所想 所做 所悟…… ……

          如何獲取call stack(調(diào)用棧)信息——之一

                   我們中的大多數(shù)人每天都會(huì)面對logging API,JDK1.4中的Logger, Log4j等,從他們生成的log文件中,我們可以知道日志產(chǎn)生的第一現(xiàn)場信息,比如源文件名,全限定類名,當(dāng)前方法名,以及記錄日志是源代碼中第幾行等,那有沒有考慮過這些信息是如何獲取的呢?
                   
                   我們先來看一段代碼
          …………
          …………
          void doSomething(){
               logger.info(
          "doSomething()調(diào)用成功");
          }

          …………
          …………
          這是我最常見的日志記錄方式。

                我下面就開始我們的追蹤以查出logging API是如何記錄上面提到的這些metadata的。

                這兒以JDK1.4中的logging API為研究對象。

                先進(jìn)入java.util.logging.Logger中,看一下info(String msg)這個(gè)方法
              public void info(String msg) {
              
          if (Level.INFO.intValue() < levelValue) {
                  
          return;
              }

              log(Level.INFO, msg);
              }
                繼續(xù)追蹤
              public void log(Level level, String msg) {
              
          if (level.intValue() < levelValue || levelValue == offValue) {
                  
          return;
              }

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

          這兒我們發(fā)現(xiàn)了一個(gè)值得關(guān)注的類 LogRecord ,從名字上猜應(yīng)該是和日志信息有關(guān)的一個(gè)類。我們來看一下它的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(調(diào)用棧)來自動(dòng)提取這些信息(方法getSourceMethodname和方法getSourceClassName),我們已經(jīng)走在正確的道路上了,繼續(xù)追查getSourceMethodname()…………
                   
              (未完)

          posted on 2005-03-13 17:58 carob 閱讀(1654) 評(píng)論(0)  編輯  收藏 所屬分類: Reflection

          主站蜘蛛池模板: 佳木斯市| 葫芦岛市| 元朗区| 瓮安县| 美姑县| 罗源县| 承德县| 高平市| 内黄县| 凤冈县| 左贡县| 那坡县| 淳化县| 长顺县| 罗江县| 静宁县| 灵武市| 锦州市| 宁城县| 阿荣旗| 新晃| 原平市| 花莲县| 区。| 鄢陵县| 白城市| 杨浦区| 孟连| 呼图壁县| 喀喇沁旗| 广德县| 英超| 石渠县| 自贡市| 德惠市| 获嘉县| 个旧市| 岚皋县| 双江| 卢龙县| 滨海县|