






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个参数,具体如下:
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级别,就没这个必要了。
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。