Platform: Eclipse 3.2
開發(fā)任何軟件都不得不處理Exception和Log,Eclipse Plug-in也是如此。不過幸運(yùn)的是,Eclipse PDE提供了記錄及顯示Exception和Log的機(jī)制:Error Log View。作為Eclipse SDK的一部分,PDE的普及率很高,所以除非你是要做RCP,不然的話用Error Log View處理Exception和Log應(yīng)該是你的最佳選擇。當(dāng)然,這也帶來了對(duì)PDE的依賴性。
使用Error Log View實(shí)際上非常簡(jiǎn)單,每個(gè)Plug-in的Activator類都有一個(gè)getLog()方法,返回一個(gè)ILog對(duì)象,這個(gè)對(duì)象就可以把Exception和Log記錄到Error Log View中。ILog對(duì)象最主要的方法就是log了,顧名思義,它接收一個(gè)IStatus類型的對(duì)象,并把其代表的狀態(tài)記錄下來。Eclipse和許多常用的插件(如JDT)實(shí)現(xiàn)了很多的IStatus,最common的就是Status類,我們可以簡(jiǎn)單地使用它,或創(chuàng)建自己的IStatus實(shí)現(xiàn)。Status的構(gòu)造函數(shù)有5個(gè)參數(shù),具體如下:
- int severity:日志的級(jí)別,可以是OK、ERROR、INFO、WARNING或CANCEL。這些常量都定義在Status類中。
- String pluginId:當(dāng)前Plug-in的ID。
- int code:Plug-in指定的狀態(tài)碼,一般如果無需指定,則使用Status.OK。
- String message:日志信息。
- Throwable exception:記錄的Exception,如果沒有Exception,則傳入null。
這樣的話,我們就可以編寫一個(gè)LogUtil類來負(fù)責(zé)日志工作,代碼如下:
<!--<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方法為日志動(dòng)作添加和刪除事件監(jiān)聽器。這些Listener可以幫助我們?cè)谌罩居涗浲瓿珊笞鲆恍╊~外的事情。例如,如果記錄的是ERROR級(jí)別的Log,那么我們可能要彈出一個(gè)Alert對(duì)話框告訴用戶出現(xiàn)了錯(cuò)誤,但如果是INFO級(jí)別,就沒這個(gè)必要了。