import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class MethodLogger {
private static final String LOG_FILE_NAME = "method.log";
private static PrintWriter writer;
static {
try {
writer = new PrintWriter(new BufferedWriter(new FileWriter(LOG_FILE_NAME)));
} catch (IOException e) {
e.printStackTrace();
}
}
private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
@Before("execution(* *(..))")
public void logMethodStart(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
String className = joinPoint.getTarget().getClass().getName();
String timeStamp = dateFormat.format(new Date());
String logMessage = String.format("[%s] %s.%s() 開始", timeStamp, className, methodName);
writer.println(logMessage);
writer.flush();
}
@After("execution(* *(..))")
public void logMethodEnd(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
String className = joinPoint.getTarget().getClass().getName();
String timeStamp = dateFormat.format(new Date());
String logMessage = String.format("[%s] %s.%s() 終了", timeStamp, className, methodName);
writer.println(logMessage);
writer.flush();
}
}