Java ex.printStackTrace() vs LOG.error(“message”,ex)

Problem Statement: Which one is best ex.printStackTrace() or LOG.error(“”,ex);

As good practice it is better to use LOG.error.
Performance wise LOG is performing better when number of calls are increased.

import java.io.IOException;

import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.RollingFileAppender;

public class LogTest {

	private static final Logger LOG = Logger.getLogger(LogTest.class);

	public static void loadLogConfig() {
		// BasicConfigurator.configure();
		Logger rootLogger = Logger.getRootLogger();
		rootLogger.setLevel(Level.INFO);
		PatternLayout layout = new PatternLayout(
				PatternLayout.DEFAULT_CONVERSION_PATTERN);
		rootLogger.addAppender(new ConsoleAppender(layout));
		try {
			RollingFileAppender rfa = new RollingFileAppender(layout,
					"performancetest.log");
			// rfa.setMaximumFileSize(1000);
			rootLogger.addAppender(rfa);

		} catch (IOException e) {
			LOG.error("", e);
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		loadLogConfig();

		long start = System.currentTimeMillis();
		calc1();
		long stop = System.currentTimeMillis();

		long start2 = System.currentTimeMillis();
		calc2();
		long stop2 = System.currentTimeMillis();

		LOG.info("Total Time Took ex.printStackTrace():" + (stop - start));
		LOG.info("Total Time Took LOG.error("",ex):" + (stop2 - start2));

		// Result 1 for LOOP_SIZE = 99000;
		// Total Time Took ex.printStackTrace():13484
		// Total Time Took LOG.error("",ex):12969

		// Result 2 for LOOP_SIZE = 99000;
		// Total Time Took ex.printStackTrace():13453
		// Total Time Took LOG.error("",ex):13171

	}

	private static int LOOP_SIZE = 100;

	public static void calc1() {
		int k;
		for (int i = 0; i < LOOP_SIZE; i++) {
			try {
				k = i / 0;
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	public static void calc2() {
		int k;
		for (int i = 0; i < LOOP_SIZE; i++) {
			try {
				k = i / 0;
			} catch (Exception ex) {
				LOG.error("", ex);
			}
		}
	}

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s