豆沙包

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

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

                   我們中的大多數(shù)人每天都會面對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為研究對象。

                先進入java.util.logging.Logger中,看一下info(String msg)這個方法
              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)了一個值得關(guān)注的類 LogRecord ,從名字上猜應(yīng)該是和日志信息有關(guān)的一個類。我們來看一下它的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)用棧)來自動提取這些信息(方法getSourceMethodname和方法getSourceClassName),我們已經(jīng)走在正確的道路上了,繼續(xù)追查getSourceMethodname()…………
                   
              (未完)

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

          主站蜘蛛池模板: 庆元县| 汪清县| 台南市| 高要市| 唐河县| 灵丘县| 确山县| 瑞丽市| 平罗县| 河北省| 裕民县| 通渭县| 拜城县| 青龙| 合水县| 宕昌县| 钦州市| 东海县| 中阳县| 乃东县| 福鼎市| 博湖县| 文登市| 兴和县| 陆川县| 新疆| 临安市| 贞丰县| 马鞍山市| 八宿县| 邯郸县| 会同县| 察雅县| 视频| 枣强县| 额济纳旗| 盘锦市| 耒阳市| 广昌县| 邵阳市| 温州市|