2012-05-16 64 views
1

我正在開發一個工作項目,並且我的任務是實現一個自定義的Java Swing庫,當用戶與Swing組件交互時,會將事件記錄到文件中。換句話說,無論用戶在GUI上與按鈕,複選框等進行交互,事件都會記錄到文件中。日誌條目必須包含事件發生位置的源文件名和行號。有一個問題:日誌記錄機制需要在中自動執行,由開發人員在庫的之外執行。可以做到嗎?這是我到目前爲止有:Java:是否有可能(在運行時)獲取未來方法調用的源文件名和行號?

自定義庫的動作監聽:

public abstract class MyActionListener implements ActionListener 
{ 
    // Prevents the developer from implementing the "actionPerformed" method 
    @Override 
    public final void actionPerformed(ActionEvent e) 
    { 
     // Do nothing 
    } 

    // Custom method 
    public void actionPerformed(MyActionEvent e) 
    { 
     doCustomMethod(); 

     // Tried obtaining the stack trace here but there's no entry 
     // in the trace for "doCustomMethod()" 
     StackTraceElement [] elements = Thread.currentThread().getStackTrace(); 
     for (StackTraceElement element : elements) 
     { 
      // print each element 
     } 
    } 

    // Forces the developer to implement this method 
    public abstract void doCustomMethod(); 
} 

自定義庫按鈕:

public class MyButton extends JButton 
{ 
    ... 

    // Custom method 
    public void addActionListener(MyActionListener l) 
    { 
     listenerList.add(MyActionListener.class, l); 
    } 
} 

開發者創建GUI:

public class TestGui extends JFrame 
{ 
    TestGui() 
    { 
     ... 

     MyButton button = new MyButton("Push"); 
     button.addActionListener(new MyActionListener() 
     { 
      public void doCustomMethod() 
      { 
       // Want to log this line number and file name, 
       // but need the library to do it; NOT the developer. 
      } 
     }); 
    } 
} 

我已經有了所有適當的邏輯,以便正確的 addActionListener() actionPerformed()方法被調用。我的問題是試圖記錄事件。我也嘗試實現自定義Java註釋,但它沒有奏效。另外,開發人員必須在構建GUI時加入-processor選項。我們試圖讓開發人員像Java Swing庫一樣使用我們的自定義Swing庫。我所實施的改變對開發者來說是透明的。

任何幫助是極大的讚賞。

+1

這聽起來像AspectJ可能是有用的...... –

回答

1

也許Logback + SLF4J可以幫助你

首次提出的logback-classic.jar,的logback-core.jar添加和SLF4J的API,在類路徑

有一個默認的配置,如果沒有出現,但如果想要獲得更詳細的配置,你可以添加一個logback.xml配置文件像這樣的東西:

<?xml version="1.0" encoding="UTF-8" ?> 

<configuration scan="true" scanPeriod="60 seconds"> 

<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> 
    <layout class="ch.qos.logback.classic.PatternLayout"> 
     <pattern>[%d{ISO8601}] [%-5level] \(%F:%L\) - %msg%n</pattern> 
    </layout> 
</appender> 

<logger name="org.hibernate" level="WARN" /> 
<logger name="org.springframework" level="INFO" /> 

<root level="INFO"> 
    <appender-ref ref="CONSOLE" /> 
</root> 

</configuration> 
+0

請你詳細說明你如何專門使用這些工具? – templatetypedef

1

約穿越什麼Component樹和增加你的聽衆每個組件(JButton的,等等 - 可以詮釋與用戶分開,你需要它)?

然後開發人員可以使用簡單的JButton(不是MyButton)。 但是,當你使用這種方法 - 你應該在創建所有組件後調用遍歷組件方法。如果將添加其他組件,您還可以添加ComponentListener以偵聽組件#添加方法並更新您的偵聽器。

0

如果您可以強制他們在doCustomMethod()實現中調用方法,則可以從堆棧跟蹤信息中訪問行號。否則,可以使用this.getClass()來查找其實現的Class名稱,並使用ASM ClassReader來查找行號/源文件。

相關問題