在開發 Eclipse 外掛或 RCP 應用程式時,經常需要將除錯資訊、操作日誌等直接輸出到 Eclipse 的 Console 視圖中,方便開發人員追蹤程式執行狀態,或讓終端使用者查看當前操作回饋。Eclipse 提供了 org.eclipse.ui.console 套件,讓我們能以程式化方式建立專屬的 Console 並寫入訊息。
以下範例示範如何建立一個名為「RCP」的 Console,並輸出帶時間戳記的訊息:
// 取得或建立 Console
MessageConsoleStream console = this.openLogConsole("RCP", "Information", "org.eclipse.workbench.ui.ide");
// 寫入訊息
console.println(new Date(System.currentTimeMillis()) + ": selected!");
public MessageConsoleStream openLogConsole(String domainName,
String stationId,
String applicationId) {
System.err.println("openLogConsole(domain=" + domainName +
", station=" + stationId + ", app=" + applicationId + ")");
// 組裝 Console 名稱,格式:Domain > Station > Application
StringBuffer consoleName = new StringBuffer(domainName);
if (stationId != null) {
consoleName.append(" > " + stationId);
if (applicationId != null) {
consoleName.append(" > " + applicationId);
}
}
// 建立 MessageConsole 及其輸出串流
MessageConsole console = new MessageConsole(consoleName.toString(), null);
final MessageConsoleStream consoleStream = console.newMessageStream();
consoleStream.setColor(Display.getDefault().getSystemColor(SWT.COLOR_BLUE));
// 向 Console Manager 註冊並顯示
IConsoleManager manager = (IConsoleManager) ConsolePlugin.getDefault().getConsoleManager();
manager.addConsoles(new IConsole[] { console });
manager.showConsoleView(console);
return consoleStream;
}
此機制適用於:
System.out.println掌握這套 API 後,即可在 Eclipse 環境中建立專業、可維護的控制台輸出體系。