/*
 * 作成日: 2006/03/05
 */
package net.sourceforge.swingx;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;

/** 自前のLogger */
public class Logger {
	// ログレベル。log4jと同じ。
	public static final int OFF   = Integer.MAX_VALUE;
	public static final int FATAL = 50000;
	public static final int ERROR = 40000;
	public static final int WARN  = 30000;
	public static final int INFO  = 20000;
	public static final int DEBUG = 10000;
	public static final int ALL   = Integer.MIN_VALUE;
	String filename = "JSpread" + new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime())+".log";
	private Class cls;
	static final SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");

	/** すべてのloggerで、INFO以上を出力したいときには、Logger.clsThreshold=INFO;とする。 */
	public static int clsThreshold = INFO;
	/** ある特定のloggerで、すべてを出力したいときには、logger.objThreshold=ALL;とする。 */
	public int objThreshold = OFF;

	private Logger(Class cls) {
		this.cls = cls;
	}
	private static HashMap map = new HashMap();
	public static Logger getLogger(Class cls) {
		Logger logger = (Logger) map.get(cls);
		if (logger == null) {
			logger = new Logger(cls);
			map.put(cls, logger);
		}
		return logger;
	}
	public void log(int level, Object msg, Throwable th) {
		if (level < clsThreshold && level < objThreshold) return;
		StringBuffer sb = new StringBuffer();
		StackTraceElement ste = getCallSideStackTraceElement();
		sb.append(formatter.format(Calendar.getInstance().getTime()));
		switch (level) {
		case FATAL:	sb.append("[FATAL]");	break;
		case ERROR:	sb.append("[ERROR]");	break;
		case WARN:	sb.append("[WARN] ");	break;
		case INFO:	sb.append("[INFO] ");	break;
		case DEBUG:	sb.append("[DEBUG]");	break;
		default:	sb.append("["+level+"]");	break;
		}
		sb.append(cls.getName());
		sb.append(".");
		sb.append(ste.getMethodName());
		sb.append("(");
		sb.append(ste.getFileName());
		sb.append(":");
		sb.append(ste.getLineNumber());
		sb.append(")- ");
		sb.append(msg);
		PrintWriter writer = null;
		try {
			writer = new PrintWriter(new FileWriter(filename, true));
			writer.println(sb.toString());
			if (th != null) {
				th.printStackTrace(writer);
			}
		} catch (IOException ex) {
			// 無視
		} finally {
			if (writer != null) writer.close();
		}
		if (level > DEBUG) System.out.println(msg);
		if (th != null) th.printStackTrace();
	}
	public void info(Object msg) { log(INFO, msg, null); }
	public void info(Object msg, Throwable th) { log(INFO, msg, th); }
	public void debug(Object msg) {	log(DEBUG, msg, null);	}
	public void debug(Object msg, Throwable th) {log(DEBUG, msg, th);	}

	private StackTraceElement getCallSideStackTraceElement() {
		StackTraceElement[] traces = new Throwable().getStackTrace();
		return traces[3];
	}
}
