package jp.bne.deno.ordermaid.common;

import java.lang.reflect.Modifier;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;
import org.apache.log4j.NDC;

public class LoggingIntercepter implements MethodInterceptor {

	private static Logger log = Logger.getLogger(LoggingIntercepter.class);

	/**
	 * 各メソッド実行前後でパラメータをログ出力する.
	 */
	public Object invoke(MethodInvocation methodInvocation) throws Throwable {
		String className = methodInvocation.getMethod().getDeclaringClass()
				.getSimpleName();
		String methodName = methodInvocation.getMethod().getName();
		NDC.push(className);
		NDC.push(methodName);
		boolean logFlg = Modifier.isPublic(methodInvocation.getMethod()
				.getModifiers());
		try {
			if (logFlg) {
				StringBuffer buf = new StringBuffer(":start ");
				Object[] args = methodInvocation.getArguments();
				for (int i = 0; i < args.length; i++) {
					buf.append("args[");
					buf.append(Integer.toString(i));
					buf.append("]=<");
					buf.append(NVL(args[i]));
					buf.append(">");
				}
				log.debug(buf.toString());
			}
			Object obj = methodInvocation.proceed();
			return obj;
		} catch (Throwable e) {
			log.error(e);
			throw e;
		} finally {
			if (logFlg) {
				log.debug(":end");
			}
			NDC.pop();
			NDC.pop();
		}
	}

	private static String NVL(Object obj) {
		if (obj == null) {
			return "null";
		}
		return obj.toString();
	}
}
