如何以Java编程方式记录传递给方法的参数

时间:2012-06-20 06:44:51

标签: java logging

如何在运行时记录传递给方法的参数?是否有任何Java库可用于此或任何可以引发以监视它的异常?

3 个答案:

答案 0 :(得分:5)

您可以使用javassist的ProxyFactoryTranslator来更改以在运行时打印参数:


使用Translator(使用新的ClassLoader):

public static class PrintArgumentsTranslator implements Translator {

    public void start(ClassPool pool) {}

    @Override
    public void onLoad(ClassPool pool, String cname)
            throws NotFoundException, CannotCompileException {
        CtClass c = pool.get(cname);

        for (CtMethod m : c.getDeclaredMethods()) 
            insertLogStatement(c, m);
        for (CtConstructor m : c.getConstructors())
            insertLogStatement(c, m);
    }

    private void insertLogStatement(CtClass c, CtBehavior m) {
        try {
            List<String> args = new LinkedList<String>();
            for (int i = 0; i < m.getParameterTypes().length; i++)
                args.add("$" + (i + 1));

            String toPrint = 
                "\"----- calling: "+c.getName() +"." + m.getName() 
                + args.toString()
                .replace("[", "(\" + ")
                .replace(",", " + \", \" + ")
                .replace("]", "+\")\""); 
            m.insertBefore("System.out.println("+toPrint+");");
        } catch (Exception e) { 
            // ignore any exception (we cannot insert log statement)
        }
    }
}

*请注意,您需要更改默认ClassLoader,以便可以对类进行检测,因此在调用main之前,您需要插入以下代码:

public static void main(String[] args) throws Throwable {
    ClassPool cp = ClassPool.getDefault();
    Loader cl = new Loader(cp);
    cl.addTranslator(cp, new PrintArgumentsTranslator());
    cl.run("test.Test$MyApp", args);  // or whatever class you want to start with
}

public class MyApp {

    public MyApp() {
        System.out.println("Inside: MyApp constructor");
    }

    public static void main(String[] args) {
        System.out.println("Inside: main method");
        new MyApp().method("Hello World!", 4711);
    }

    public void method(String string, int i) {
        System.out.println("Inside: MyApp method");
    }
}

输出:

----- calling: test.Test$MyApp.main([Ljava.lang.String;@145e044)
Inside: main method
----- calling: test.Test$MyApp.Test$MyApp()
Inside: MyApp constructor
----- calling: test.Test$MyApp.method(Hello World!, 4711)
Inside: MyApp method

使用ProxyFactory

public class Test {

    public String method(String string, int integer) {
        return String.format("%s %d", string, integer);
    }

    public static void main(String[] args) throws Exception {

        ProxyFactory f = new ProxyFactory();
        f.setSuperclass(Test.class);

        Class<?> c = f.createClass();
        MethodHandler mi = new MethodHandler() {
            public Object invoke(
                    Object self, Method m, Method proceed, Object[] args)
                throws Throwable {

                System.out.printf("Method %s called with %s%n", 
                                  m.getName(), Arrays.toString(args));

                // call the original method
                return proceed.invoke(self, args);
            }
        };

        Test foo = (Test) c.newInstance();
        ((Proxy) foo).setHandler(mi);
        foo.method("Hello", 4711);
    }
}

输出:

Method method called with [Hello, 4711]

答案 1 :(得分:3)

你应该尝试使用AOP。以下示例可以或多或少地执行您想要的操作:How to use AOP with AspectJ for logging?

答案 2 :(得分:1)

我认为您可以注册MBean,然后才能使用JMX进行检查。

链接: http://docs.oracle.com/cd/E19159-01/819-7758/gcitp/index.html