豆沙包

          …… …… 所學(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為研究對象。

                先進(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 閱讀(1646) 評論(0)  編輯  收藏 所屬分類: Reflection

          主站蜘蛛池模板: 马龙县| 兴文县| 甘孜县| 夏河县| 荥阳市| 凤冈县| 安丘市| 麻江县| 武安市| 长葛市| 慈利县| 柳州市| 宣汉县| 玉树县| 哈巴河县| 镶黄旗| 通化市| 涪陵区| 老河口市| 江口县| 滁州市| 香河县| 武威市| 松潘县| 衡山县| 集贤县| 德清县| 耿马| 元阳县| 高安市| 嵊州市| 察哈| 格尔木市| 霍邱县| 泾川县| 昌黎县| 淮安市| 电白县| 清远市| 普定县| 乃东县|