嘟嘟

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  26 Posts :: 0 Stories :: 6 Comments :: 0 Trackbacks
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级别,就没这个必要了。

posted on 2007-05-17 19:17 fyp1210 阅读(322) 评论(0)  编辑  收藏 所属分类: eclipse plugin

只有注册用户登录后才能发表评论。


网站导航: