如何在 Eclipse 的 Error Log 中顯示外掛程式自己的日誌

來源:互聯網
上載者:User

開發任何軟體都不得不處理 Exception 和 Log,Eclipse Plug-in 也是如此。不過幸運的是,Eclipse PDE 提供了記錄及顯示Exception和Log的機制:Error Log View。作為 Eclipse SDK 的一部分,PDE 的普及率很高,所以除非你是要做 RCP,不然的話用 Error Log View處理 Exception
和 Log 應該是你的最佳選擇。當然,這也帶來了對 PDE 的依賴性。

使用 Error Log View實際上非常簡單,每個 Plug-in 的 Activator 類都有一個 getLog() 方法,返回一個 ILog 對象,這個對象就可以把 Exception 和 Log 記錄到 Error Log View 中。ILog 對象最主要的方法就是 log 了,顧名思義,它接收一個 IStatus類型的對象,並把其代表的狀態記錄下來。Eclipse 和許多常用的外掛程式(如JDT)實現了很多的 IStatus,最 common 的就是Status類,我們可以簡單地使用它,或建立自己的
IStatus 實現。Status的建構函式有5個參數,具體如下:

 

這樣的話,我們就可以編寫一個LogUtil類來負責日誌工作,代碼如下:

 

package demo;import org.eclipse.core.runtime.ILog;import org.eclipse.core.runtime.Status;import xxx.PluginActivator;public class EclipseErrorLog{    private static ILog logger = null;    static    {        logger = PluginActivator.getDefault().getLog();    }    private EclipseErrorLog()    {        // nothing to do    }    public static void logCancel(String message, Throwable exception)    {        logger.log(new Status(Status.CANCEL, PluginActivator.PLUGIN_ID, Status.OK, message, exception));    }    public static void logError(String message, Throwable exception)    {        logger.log(new Status(Status.ERROR, PluginActivator.PLUGIN_ID, Status.OK, message, exception));    }    public static void logInfo(String message, Throwable exception)    {        logger.log(new Status(Status.INFO, PluginActivator.PLUGIN_ID, Status.OK, message, exception));    }    public static void logOk(String message, Throwable exception)    {        logger.log(new Status(Status.OK, PluginActivator.PLUGIN_ID, Status.OK, message, exception));    }    public static void logWarning(String message, Throwable exception)    {        logger.log(new Status(Status.WARNING, PluginActivator.PLUGIN_ID, Status.OK, message, exception));    }}

 

除此之外,我們還可以通過 ILog 的 addLogListener 方法和 removeLogListener 方法為日誌動作添加和刪除事件監聽器。這些Listener 可以協助我們在日誌記錄完成後做一些額外的事情。例如,如果記錄的是 ERROR 層級的 Log,那麼我們可能要彈出一個Alert 對話方塊告訴使用者出現了錯誤,但如果是 INFO 層級,就沒這個必要了。

 

 

備忘:

本文轉載自:http://hintcnuie.javaeye.com/blog/787932

  • int severity:日誌的層級,可以是OK、ERROR、INFO、WARNING或CANCEL。這些常量都定義在Status類中。
  • String pluginId:當前Plug-in的ID。
  • int code:Plug-in指定的狀態代碼,一般如果無需指定,則使用Status.OK。
  • String message:日誌資訊。
  • Throwable exception:記錄的Exception,如果沒有Exception,則傳入null。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.