Eclipse console logging tip

Started by mot, February 09, 2008, 21:01:43

Previous topic - Next topic

mot

When I'm debugging I do a lot of logging and usually don't bother to clean it up after I finish. So the log output gets more and more cluttered with output from different parts of the game and it doesn't make much sense when it's all mixed together.

I had noticed before that when my game throws a runtime exception, the Eclipse console will parse the stack dump and make the class names clickable, so you can get to the source of the exception very quickly.

Then I realized this could be extended to all my log output. Each line of logging output in the Eclipse console can have a clickable link that will take me directly to the place from which the log output was printed!

With Java reflection it's pretty easy and turns out to be very useful. It has some limitations, such as Eclipse getting confused when you have several projects open in your workspace that have similar filenames etc. but it works fine for me. I'm sure this can be improved to be more precise, but I haven't found a way how to do that yet.

Here is a part of Log.java that contains the trick:

public class Log {
	public static void log( Object message, Throwable throwable ) {
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append( message );

		// Clickable link at end of line
		for ( StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace() ) {
			if ( stackTraceElement.getFileName() != null && stackTraceElement.getClassName().equals( Log.class.getName() ) == false ) {
				stringBuffer.append( " (" );
				stringBuffer.append( stackTraceElement.getFileName() );
				stringBuffer.append( ":" );
				stringBuffer.append( stackTraceElement.getLineNumber() );
				stringBuffer.append( ")" );
				break;
			}
		}

		// Stack dump if exception is given.
		stringBuffer.append( '\n' );
		if ( throwable != null ) {
			stringBuffer.append( throwable.toString() );
			stringBuffer.append( '\n' );
			for ( StackTraceElement stackTraceElement : throwable.getStackTrace() ) {
				stringBuffer.append( stackTraceElement.toString() );
				stringBuffer.append( '\n' );
			}
			if ( throwable.getCause() != null ) {
				stringBuffer.append( "Caused by:\n" );
				stringBuffer.append( throwable.getCause().toString() );
				stringBuffer.append( '\n' );
				for ( StackTraceElement stackTraceElement : throwable.getCause().getStackTrace() ) {
					stringBuffer.append( stackTraceElement.toString() );
					stringBuffer.append( '\n' );
				}
			}
		}

		System.out.println( message );
	}
}



I haven't used any fancy logging libraries for Java, so if any of them already does this, let me know.

mot