Platform: Eclipse 3.2
開發任何軟件都不得不處理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個參數,具體如下:
- 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。
這樣的話,我們就可以編寫一個LogUtil類來負責日志工作,代碼如下:
<!--<br><br>Code highlighting produced by Actipro CodeHighlighter (freeware)<br>http://www.CodeHighlighter.com/<br><br>-->
import org.eclipse.core.runtime.ILog;
import org.eclipse.core.runtime.Status;
public class LogUtil {
private static LogUtil instance = null;
private ILog logger = null;
private LogUtil() {
logger = Activator.getDefault().getLog();
}
public static LogUtil getInstance() {
if (instance == null) {
instance = new LogUtil();
}
return instance;
}
public void log(int severity, String message, Throwable exception) {
logger.log(new Status(severity, Activator.getDefault().getPluginID(),
Status.OK, message, exception));
}
public void logCancel(String message, Throwable exception) {
logger.log(new Status(Status.CANCEL, Activator.getDefault()
.getPluginID(), Status.OK, message, exception));
}
public void logError(String message, Throwable exception) {
logger.log(new Status(Status.ERROR, Activator.getDefault()
.getPluginID(), Status.OK, message, exception));
}
public void logInfo(String message, Throwable exception) {
logger.log(new Status(Status.INFO,
Activator.getDefault().getPluginID(), Status.OK, message,
exception));
}
public void logOk(String message, Throwable exception) {
logger.log(new Status(Status.OK, Activator.getDefault().getPluginID(),
Status.OK, message, exception));
}
public void logWarning(String message, Throwable exception) {
logger.log(new Status(Status.WARNING, Activator.getDefault()
.getPluginID(), Status.OK, message, exception));
}
}
除此之外,我們還可以通過ILog的addLogListener方法和removeLogListener方法為日志動作添加和刪除事件監聽器。這些Listener可以幫助我們在日志記錄完成后做一些額外的事情。例如,如果記錄的是ERROR級別的Log,那么我們可能要彈出一個Alert對話框告訴用戶出現了錯誤,但如果是INFO級別,就沒這個必要了。