Friday, July 10, 2009

Eclipse RCP : Redirecting eclipse errors to log4j

Its sometimes tedious to find the real exception occured when using an eclipse based application. Since it goes under the workspace/.metadata/.log file. It takes a while to figure this out. But most of the desktop application do write to a log file of its own. So when using eclipse using two log files to know about the application is kind of not nice.

But still eclipse provides a way to listen to the log messages of its own. So if the application uses its own logging , it can listen to the eclipse log and add it to its own logger. Here we will look at connecting eclipse log messages to the log4j logger.

Eclipse Platform provides a method to add listeners Platform.addLogListener(ILogListener);

So how do we add the listener to the Platform. In the Activator of the application plugin's start method, add the following.


public class Activator extends AbstractUIPlugin {

private ILogListener listener;


@Override
public void start(final BundleContext context) throws Exception {
super.start(context);
plugin = this;
listener = new Listener();
Platform.addLogListener(listener);
}

@Override
public void stop(final BundleContext context) throws Exception {
Platform.removeLogListener(listener);
listener = null;
plugin = null;
super.stop(context);
}

}


Now every error/warning eclipse logs to its .log file under .metadata directory will be sent to the log listener. How does the log listener handle the events from the eclipse?


package com.logging;
public class Listener implements ILogListener {
private static final Logger LOGGER = Logger.getLogger(Listener.class.getName());

@Override
public void logging(final IStatus status, final String plugin) {
if (status.getSeverity() == IStatus.WARNING) {
if (status.getException() == null) {
LOGGER.warn(status.getMessage());
} else {
LOGGER.warn(status.getMessage() + status.getException());
}
} else if (status.getSeverity() == IStatus.ERROR) {
if (status.getException() == null) {
LOGGER.error(status.getMessage());
} else {
LOGGER.error(status.getMessage()+status.getException());
}
}
}
}


Now all the eclipse errors and warnings will go to the logger which is configured for Listener.class.getName().

To get all the log messages from the eclipse. the log4j.properties

log4j.category.com.logging.Listener=all

This will log all the errors and warnings from the eclipse application to the log4j's log file or console as configured.

3 comments:

Ajay said...
This comment has been removed by the author.
Ajay said...

Hello KSG,

The code snippet Shows a
listener = new LogListener() ;

But u have declared the class below as Listener

Either Refactor the below class to LogListener
or please change the code as
listener = new Listener();

Thanks ,
Ajay

KSG said...

thanks for noting it.