// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.*;
import java.util.*;

aspect Trace {
    HashMap pws = new HashMap();
    HashMap ind = new HashMap();
    PrintWriter getPrintWriter() {
        String thrnam = Thread.currentThread().getName();
        if(pws.get(thrnam) == null) {
            try {
                pws.put(thrnam, new PrintWriter(new FileWriter("Trace-" + thrnam + ".log")));
            } catch(IOException ex) {
                ex.printStackTrace();
                System.exit(1);
            }
        }
        return (PrintWriter)pws.get(thrnam);
    }
    public void increaseIndent() {
        String thrnam = Thread.currentThread().getName();
        ind.put(thrnam, getIndent() + "    ");
    }
    public void decreaseIndent() {
        String thrnam = Thread.currentThread().getName();
        ind.put(thrnam, getIndent().substring(4));
    }
    public String getIndent() {
        String thrnam = Thread.currentThread().getName();
        if(ind.get(thrnam) == null) {
            ind.put(thrnam, "");
        }
        return (String)ind.get(thrnam);
    }
    pointcut alltrace() : call(* *.*(..)) && !within(Trace);
    before() : alltrace() {
        getPrintWriter().print(getIndent() + "calling : " + thisJoinPoint.getSignature() + " with arguments");
        Object[] o = thisJoinPoint.getArgs();
        for(int i = 0; i < o.length; i++) {
            getPrintWriter().print(" " + (o[i] != null ? o[i].getClass().getName() + " " : "") + o[i]);
        }
        getPrintWriter().println();
        getPrintWriter().flush();
        increaseIndent();
    }
    after() returning(Object o) : alltrace() {
        decreaseIndent();
        getPrintWriter().println(getIndent() + "returning from : " + thisJoinPoint.getSignature() + " return value " + (o != null ? o.getClass().getName() + " " : "") + o);
        getPrintWriter().flush();
    }
    after() throwing(Exception ex) : alltrace() {
        decreaseIndent();
        getPrintWriter().println(getIndent() + "exception in : " + thisJoinPoint.getSignature() + " " + ex);
        getPrintWriter().flush();
    }
}
