package com.orientechnologies.common.log;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.LogRecord;

public class OLogFormatter extends Formatter {

	private static final DateFormat	dateFormat	= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS");

	@Override
	public String format(final LogRecord record) {
		if (record.getThrown() == null) {
			return customFormatMessage(record);
		}

		// FORMAT THE STACK TRACE
		final StringBuilder buffer = new StringBuilder();
		buffer.append(record.getMessage());

		Throwable current = record.getThrown();

		while (current != null) {
			buffer.append("\n" + current.getMessage());

			for (StackTraceElement stackTraceElement : record.getThrown().getStackTrace()) {
				buffer.append("\n-> ");
				buffer.append(stackTraceElement.toString());
			}
			current = current.getCause();
		}

		return buffer.toString();
	}

	private String customFormatMessage(final LogRecord iRecord) {
		Level iLevel = iRecord.getLevel();
		String iMessage = iRecord.getMessage();
		Object[] iAdditionalArgs = iRecord.getParameters();
		String iRequester = getSourceClassSimpleName(iRecord.getSourceClassName());

		final StringBuilder buffer = new StringBuilder();
		buffer.append('\n');
		synchronized (dateFormat) {
			buffer.append(dateFormat.format(new Date()));
		}
		buffer.append(' ');
		buffer.append(iLevel.getName().substring(0, 4));
		if (iRequester != null) {
			buffer.append(" [");
			buffer.append(iRequester);
			buffer.append(']');
		}
		buffer.append(' ');

		// FORMAT THE MESSAGE
		try {
			buffer.append(String.format(iMessage, iAdditionalArgs));
		} catch (Exception e) {
			buffer.append(iMessage);
		}

		return buffer.toString();
	}

	private String getSourceClassSimpleName(final String iSourceClassName) {
		return iSourceClassName.substring(iSourceClassName.lastIndexOf(".") + 1);
	}
}

@@ -385,16 +385,160 @@
 S%22);%0D%0A%0D%0A
+%09/**%0D%0A%09 * The end-of-line character for this platform.%0D%0A%09 */%0D%0A%09private static final String%09%09%09EOL%09%09%09%09%09= System.getProperty(%22line.separator%22);%0D%0A%0D%0A
 %09@Overri
@@ -541,16 +541,16 @@
 erride%0D%0A
-
 %09public 
@@ -892,15 +892,20 @@
 end(
-%22%5Cn%22 + 
+EOL).append(
 curr
@@ -1033,11 +1033,21 @@
 end(
-%22%5Cn
+EOL).append(%22
 -%3E %22
@@ -1536,12 +1536,11 @@
 end(
-'%5Cn'
+EOL
 );%0D%0A

Patch by Laszlo Hordos to fix issue 646