Monday, March 2, 2009

Eclipse : Writing to the console in a RCP Application

When you want to add console message to the eclipse console view, there is no easiest way to do this. The sysout/syserr messages will go on the console where you have the application if you run it with -consoleLog option.

How do we show the messages on the console view eclipse provides. First of all we have to add the console view to the perspective. The console view is part of the org.eclipse.ui.console plugin, so add it to the dependencies if you dont have it already.

Now add the ConsoleView to the perspective in the createInitialLayout method ( the following snippet is written with the RCP Mail example )

public void createInitialLayout(IPageLayout layout) {
String editorArea = layout.getEditorArea();

layout.addStandaloneView(NavigationView.ID, false, IPageLayout.LEFT,
0.25f, editorArea);
IFolderLayout folder = layout.createFolder("messages", IPageLayout.TOP,
0.5f, editorArea);
folder.addPlaceholder(View.ID + ":*");

IFolderLayout consoleFolder = layout.createFolder("console",
IPageLayout.BOTTOM, 0.65f, "messages");

Now if you run the application you can see the console view at the bottom of the Messages view of the RCP Mail application. But now there are no open consoles on the console view. Now let us take an example, whenever a Messages view is opened we want to write something to the console.

public class OpenViewAction extends Action {

private final IWorkbenchWindow window;
private int instanceNum = 0;
private final String viewId;
MessageConsole messageConsole;

public OpenViewAction(IWorkbenchWindow window, String label, String viewId) {
this.window = window;
this.viewId = viewId;
// The id is used to refer to the action in a menu or toolbar
// Associate the action with a pre-defined command, to allow key
// bindings.


public void run() {
if (window != null) {
try {
int instance = instanceNum++;

messageConsole = getMessageConsole();
MessageConsoleStream msgConsoleStream = messageConsole

new IConsole[] { messageConsole });

msgConsoleStream.println(viewId + Integer.toString(instance));

} catch (PartInitException e) {
MessageDialog.openError(window.getShell(), "Error",
"Error opening view:" + e.getMessage());

private MessageConsole getMessageConsole() {
if (messageConsole == null) {
messageConsole = new MessageConsole("RCPMail", null);
new IConsole[] { messageConsole });

return messageConsole;


Now every new view opened will write the ViewID to the RCPMail console we created.

Have fun!

No comments: