做插件開發的都知道當應用跑不起來了就去看看workspace里的.log文件,錯誤信息很詳細,那樣解決問題就方便多了,這個功能很好,所以學習了下,和大家分享下,實現的原理也就一行代碼
Java代碼
Platform.getLog(Platform.getBundle(bundleID)).log(
newStatus(serverity,?bundleID,?code,?message,?t));
Platform.getLog(Platform.getBundle(bundleID)).log(
new Status(serverity, bundleID, code, message, t));
原理知道了,那么怎么樣得到像eclipse生成.log里的那些效果呢?
runtime包下有個Status類它繼承IStatus,大家可以去看看它的源碼,我說到它的原因就是因為它包含了eclipse的warning,error以及info,這三類log都是最常用的,下面我也不啰嗦了,貼代碼
Java代碼
packagecom.bjgtt.msap.workbench.utilities;
importorg.eclipse.core.runtime.Platform;
importorg.eclipse.core.runtime.Status;
publicclassLogUtil?{
publicstaticvoidlogError(Throwable?t)?{
logError(null,?t.getMessage(),?t);
}
publicstaticvoidlogError(String?bundleID,?Throwable?t)?{
logError(bundleID,?t.getMessage(),?t);
}
publicstaticvoidlogError(String?bundleID,?String?message,?Throwable?t)?{
log(bundleID,?message,?t,?Status.ERROR,?Status.OK);
}
publicstaticvoidlogWarning(String?message)?{
log(null,?message,null,?Status.WARNING,?Status.OK);
}
publicstaticvoidlogError(String?bundleID,?String?message)?{
logError(bundleID,?message,null);
}
publicstaticvoidlog(String?bundleID,?String?message,?Throwable?t,intserverity,intcode)?{
if(bundleID?==null)?{
bundleID?=?Activator.getDefault().getBundle().getSymbolicName();
}
Platform.getLog(Platform.getBundle(bundleID)).log(newStatus(serverity,?bundleID,?code,?message,?t));
}
}
package com.bjgtt.msap.workbench.utilities;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
public class LogUtil {
public static void logError(Throwable t) {
logError(null, t.getMessage(), t);
}
public static void logError(String bundleID, Throwable t) {
logError(bundleID, t.getMessage(), t);
}
public static void logError(String bundleID, String message, Throwable t) {
log(bundleID, message, t, Status.ERROR, Status.OK);
}
public static void logWarning(String message) {
log(null, message, null, Status.WARNING, Status.OK);
}
public static void logError(String bundleID, String message) {
logError(bundleID, message, null);
}
public static void log(String bundleID, String message, Throwable t, int serverity, int code) {
if (bundleID == null) {
bundleID = Activator.getDefault().getBundle().getSymbolicName();
}
Platform.getLog(Platform.getBundle(bundleID)).log(new Status(serverity, bundleID, code, message, t));
}
}
大家看到了上面的類中有六個方法,歸根到底都是調的最下面的方法,所以代碼就變得簡單多了,為大家介紹這些方法的使用吧:
首先就是logError(Throwable t)方法:
Error很顯然就是捕獲的異常信息了
logError(String bundleID, Throwable t) 有上面的方法了,這個方面就用不著了
接著就是logError(String bundleID, String message, Throwable t)
方法了
用了組裝錯誤消息
logWarning(String message) :
看名字大家就知道是告警日志了,最常用的地方就是你需要得到一個對象的實例,而這個實例為null那么你就可以使用這個方法來記錄日志了
logError(String bundleID, String message) :
插件錯誤信息,bundleID就是你的插件ID