Log4j拿到當前執行語句的實現

LoggingEvent中的

  public LocationInfo getLocationInformation() {
    if(locationInfo == null) {
      locationInfo = new LocationInfo(new Throwable(), fqnOfCategoryClass);
    }
    return locationInfo;
  }


LocationInfo中的

public LocationInfo(Throwable t, String fqnOfCallingClass) {
      if(t == null || fqnOfCallingClass == null)
	return;
      if (getLineNumberMethod != null) {
          try {
              Object[] noArgs = null;
              Object[] elements =  (Object[]) getStackTraceMethod.invoke(t, noArgs);
              String prevClass = NA;
              for(int i = elements.length - 1; i >= 0; i--) {
                  String thisClass = (String) getClassNameMethod.invoke(elements[i], noArgs);
                  if(fqnOfCallingClass.equals(thisClass)) { 
                      int caller = i + 1;
                      if (caller < elements.length) {
                      className = prevClass;
                      methodName = (String) getMethodNameMethod.invoke(elements[caller], noArgs);
                      fileName = (String) getFileNameMethod.invoke(elements[caller], noArgs);
                          if (fileName == null) {
                              fileName = NA;
                          }
                          int line = ((Integer) getLineNumberMethod.invoke(elements[caller], noArgs)).intValue();
                          if (line < 0) {
                              lineNumber = NA;
                          } else {
                              lineNumber = String.valueOf(line);
                          }
                          StringBuffer buf = new StringBuffer();
                          buf.append(className);
                          buf.append(".");
                          buf.append(methodName);
                          buf.append("(");
                          buf.append(fileName);
                          buf.append(":");
                          buf.append(lineNumber);
                          buf.append(")");
                          this.fullInfo = buf.toString();
                      }
                      return;
                  }
                  prevClass = thisClass;
              }
              return;
          } catch(IllegalAccessException ex) {
              LogLog.debug("LocationInfo failed using JDK 1.4 methods", ex);
          } catch(InvocationTargetException ex) {
              if (ex.getTargetException() instanceof InterruptedException
                      || ex.getTargetException() instanceof InterruptedIOException) {
                  Thread.currentThread().interrupt();
              }
              LogLog.debug("LocationInfo failed using JDK 1.4 methods", ex);
          } catch(RuntimeException ex) {
              LogLog.debug("LocationInfo failed using JDK 1.4 methods", ex);
          }
      }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章