/**
 * 
 */
package com.ejie.ad74a.context.log;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.ThrowableProxy;
import ch.qos.logback.core.LayoutBase;

/**
 * 
 * @author JBHG
 *
 */
public class LogLayout extends LayoutBase<ILoggingEvent> {

	private static final int STRINGBUILDER_SIZE = 512;
	private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
	private static final String SEPARATOR = " ~~ ";

	private String appCode = null;

	@Override
	public String doLayout(ILoggingEvent paramE) {
		StringBuilder traza = new StringBuilder(STRINGBUILDER_SIZE);
		traza.append(dateFormat.format(paramE.getTimeStamp())).append(SEPARATOR);
		traza.append(paramE.getThreadName()).append(SEPARATOR);
		traza.append(paramE.getLoggerContextVO().getBirthTime()).append(SEPARATOR);
		traza.append(this.appCode).append(SEPARATOR);
		traza.append(paramE.getLoggerName()).append(SEPARATOR);
		traza.append("[").append(paramE.getLevel()).append("]").append(SEPARATOR);
		traza.append(paramE.getFormattedMessage());

		if (paramE.getThrowableProxy() != null) {
			ThrowableProxy throwableProxy = (ThrowableProxy) paramE.getThrowableProxy();
			traza.append(SEPARATOR).append(getStackTrace(throwableProxy.getThrowable()));
		}

		traza.append("\r\n");
		return traza.toString();
	}

	/**
	 * 
	 * @param appCode
	 *            String
	 */
	public void setAppCode(String appCode) {
		this.appCode = appCode;
	}

	/*
	 * Metodo para obtener la pila de llamadas de una excepcion
	 */
	private static String getStackTrace(Throwable t) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw, true);
		t.printStackTrace(pw);
		pw.flush();
		sw.flush();
		return sw.toString();
	}
}
