使用Javassist记录方法调用和参数值,如何在每个检测类中显示记录器类?

时间:2015-04-04 21:43:08

标签: java logging javassist

该工具(在this repo中)包含3个类(如下所示)。问题是如何使我的ParaTracer.Logger课程在我​​的每个课程中都可见(例如下面显示的java.util.Random)。声明cp.importPackage( "ParaTracer.Logger");似乎不起作用,我收到此错误:

java.lang.NoClassDefFoundError: ParaTracer/Logger at java.util.Random.nextLong(Random.java)

我尝试在每个已检测的类中动态加载Logger类。但似乎我错误地使用Class.getMethod(),或者Javassist编译器太原始而无法编译动态类加载代码。我收到这个错误:

javassist.CannotCompileException: [source error] getMethod(java.lang.String,java.lang.Class,java.lang.Class) not found in java.lang.Class

使用定义Premain-Class的MANIFEST.MF文件将以下3个类导出到JAR文件中,并在使用该开关运行任何已检测程序时传递给JVM:

-javaagent:/Path/To/ParaTracerAgent.jar

以下是3个班级。

package ParaTracer;

import java.lang.instrument.Instrumentation;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.CtNewConstructor;
import javassist.CtNewMethod;

public class ParaTracer {

    private static volatile Instrumentation instr;

    public static void premain(String agentArgs, Instrumentation inst) {
        instr = inst;
        SimpleClassTransformer transformer = new SimpleClassTransformer();
        inst.addTransformer( transformer, false );
    }
}

变压器类:

package ParaTracer;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;
import java.util.HashMap;
import java.util.HashSet;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;


public class SimpleClassTransformer implements ClassFileTransformer {

    public HashMap< String, HashSet< String > > mInstrumentedMethods;

    public SimpleClassTransformer() {
        mInstrumentedMethods = new HashMap< String, HashSet< String > >();

        mInstrumentedMethods.put( "java.util.Random", new HashSet< String >() );
        mInstrumentedMethods.get( "java.util.Random").add( "nextLong" );
    }

    @Override
    public byte[] transform(
        ClassLoader       loader,
        String            className,
        Class<?>          classBeingRedefined,
        ProtectionDomain  protectionDomain,
        byte[]            classfileBuffer) throws IllegalClassFormatException {

        System.err.println( "---- Instrumenting: " + className );

        byte[] byteCode = classfileBuffer;

        String normalizedClassName = className.replaceAll("/", ".");

        if ( mInstrumentedMethods.containsKey( normalizedClassName ) ) {
            try {
                ClassPool cp = ClassPool.getDefault();

                cp.importPackage( "ParaTracer.Logger");

                CtClass cc = cp.get( normalizedClassName );

                for( String method : mInstrumentedMethods.get( normalizedClassName ) ) {
                    CtMethod  m  = cc.getDeclaredMethod( method );

                    StringBuilder sbs = new StringBuilder();
                    sbs.append( "long tid = Thread.currentThread().getId();" );
                    sbs.append( "StringBuilder sbArgs = new StringBuilder();" );
                    sbs.append( "sbArgs.append( System.identityHashCode( $0 ) );" );
                    CtClass[] pTypes = m.getParameterTypes();
                    for( int i=0; i < pTypes.length; ++i ) {
                        CtClass pType = pTypes[i];
                        if ( pType.isPrimitive() ) {
                            sbs.append( "sbArgs.append( \", \" + $args[" + i + "] );" );
                        } else {
                            sbs.append( "sbArgs.append( \", \" + System.identityHashCode( $args[" + i + "] ) );" );
                        }
                    }
                    sbs.append( "ParaTracer.Logger.pushArgs( tid, sbArgs.toString() );" );
                    sbs.append( "StringBuilder sb = new StringBuilder();" );
                    sbs.append( "sb.append( tid + \" : " + m.getLongName() + ".<START>(\" );" );
                    sbs.append( "sb.append( sbArgs.toString() );" );
                    sbs.append( "sb.append( \")\" );" );
                    sbs.append( "ParaTracer.Logger.print( sb.toString() );" );

                    m.insertBefore("{" + sbs.toString() + "}");

                    StringBuilder sbe = new StringBuilder();
                    sbe.append( "long tid = Thread.currentThread().getId();" );
                    sbe.append( "String args = ParaTracer.Logger.popArgs( tid );" );
                    sbe.append( "StringBuilder sb = new StringBuilder();" );
                    sbe.append( "sb.append( tid + \" : " + m.getLongName() + ".<END>(\" );" );
                    sbe.append( "sb.append( args );" );
                    sbe.append( "sb.append( \")\" );" );
                    sbe.append( "ParaTracer.Logger.print( sb.toString() );" );

                    m.insertAfter("{" + sbe.toString() + "}");
                }
                byteCode = cc.toBytecode();
                cc.detach();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return byteCode;
    }
}

线程安全记录器类由:

给出
package ParaTracer;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Stack;

public class Logger {

    private static String loggerFilePath = "\"/some/fixed/path\"";
    private static FileWriter   fw;
    private static PrintWriter  out;
    private static HashMap< Long, Stack<String> > callStacks;

    public static synchronized void pushArgs( long tid, String args ) {
        try {
            init();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if ( ! callStacks.containsKey( tid ) ) {
            callStacks.put( tid, new Stack<String>() );
        }
        callStacks.get( tid ).push( args );
    }

    public static synchronized String popArgs( long tid ) {
        assert( callStacks.containsKey( tid ) );
        assert( ! callStacks.get( tid ).empty() );
        return callStacks.get( tid ).pop();
    }

    public static synchronized void shutdown() {
        if ( fw == null ) return;
        try {
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static synchronized void print( String str ) {
        try {
            init();
        } catch (IOException e) {
            e.printStackTrace();
        }
        out.print( str );
    }

    private static void init() throws IOException {
        if ( fw != null ) return;
        fw  = new FileWriter( loggerFilePath );
        out = new PrintWriter( fw );
        callStacks = new HashMap< Long, Stack<String> >();
    }
}

2 个答案:

答案 0 :(得分:6)

根据the documentation for Java agents,代理类由 system 类加载器加载。但是,如果您想要检测核心Java类并将它们引用到您自己的自定义类中,则该类需要可用于 bootstrap 类加载器而不是系统类。

将您的Logger类移动到单独的JAR文件中,并在代理JAR清单的Boot-Class-Path属性中列出该文件:

Boot-Class-Path: ParaTracerLogger.jar

现在,logger类在引导加载程序中可见,并且可以通过已检测的java.lang类看到。

答案 1 :(得分:1)

我最终得到的ClassFileTransformer.tranform方法如下:

基本上,每次有要写出的消息并且 该消息附加到输出文件时,Javassist插入的代码会重新打开相同的日志文件。拥有单独的日志文件非常重要,因为重定向标准输出/错误将导致受污染的日志文件(如果这些流已经被已检测的应用程序使用(通常是这种情况))。

@Override
public byte[] transform(
        ClassLoader       loader,
        String            className,
        Class<?>          classBeingRedefined,
        ProtectionDomain  protectionDomain,
        byte[]            classfileBuffer)
                throws IllegalClassFormatException {

    byte[] byteCode = classfileBuffer;

    String normalizedClassName = className.replaceAll("/", ".");
    System.out.println( "\tNormalized: " + normalizedClassName );

    ClassMonitorSet classMonitorSet = monitorClass( normalizedClassName );
    if ( classMonitorSet != null ) {
        System.out.println( "\tMonitoring: " + normalizedClassName );
        try {
            ClassPool cp = ClassPool.getDefault();
            CtClass cc = cp.get( normalizedClassName );

            for( String methodName : classMonitorSet.monitorSet ) {
                CtMethod[]  methods  = cc.getDeclaredMethods( methodName );
                for( CtMethod method : methods ) {

                    StringBuilder sbs = new StringBuilder();
                    sbs.append( "long tid = Thread.currentThread().getId();" );
                    sbs.append( "StringBuilder sbArgs = new StringBuilder();" );
                    sbs.append( "sbArgs.append( System.identityHashCode( $0 ) );" );
                    CtClass[] pTypes = method.getParameterTypes();
                    for( int i=0; i < pTypes.length; ++i ) {
                        CtClass pType = pTypes[i];
                        if ( pType.isPrimitive() ) {
                            sbs.append( "sbArgs.append( \", \" + $args[" + i + "] );" );
                        } else {
                            sbs.append( "sbArgs.append( \", \" + System.identityHashCode( $args[" + i + "] ) );" );
                        }
                    }
                    sbs.append( "StringBuilder sb = new StringBuilder();" );
                    sbs.append( "sb.append( tid + \" : " + method.getLongName() + ".<START>(\" );" );
                    sbs.append( "sb.append( sbArgs.toString() );" );
                    sbs.append( "sb.append( \")\" );" );
                    sbs.append( "String fPath = \"/path/to/log.out\";" );
                    sbs.append( "try {" );
                    sbs.append( "   java.io.FileWriter  fw  = new java.io.FileWriter( fPath, true );" );
                    sbs.append( "   java.io.PrintWriter out = new java.io.PrintWriter( fw, true );" );
                    sbs.append( "   out.println( sb.toString() );" );
                    sbs.append( "   fw.close();" );
                    sbs.append( "} catch (java.io.IOException e) {" );
                    sbs.append( "   e.printStackTrace();" );
                    sbs.append( "}" );

                    method.insertBefore("{" + sbs.toString() + "}");

                    StringBuilder sbe = new StringBuilder();
                    sbe.append( "long tid = Thread.currentThread().getId();" );
                    sbe.append( "StringBuilder sb = new StringBuilder();" );
                    sbe.append( "sb.append( tid + \" : " + method.getLongName() + ".<END>(*)\" );" );
                    sbe.append( "String fPath = \"/path/to/log.out\";" );
                    sbe.append( "try {" );
                    sbe.append( "   java.io.FileWriter  fw  = new java.io.FileWriter( fPath, true );" );
                    sbe.append( "   java.io.PrintWriter out = new java.io.PrintWriter( fw, true );" );
                    sbe.append( "   out.println( sb.toString() );" );
                    sbe.append( "   fw.close();" );
                    sbe.append( "} catch (java.io.IOException e) {" );
                    sbe.append( "   e.printStackTrace();" );
                    sbe.append( "}" );

                    method.insertAfter("{" + sbe.toString() + "}");
                }
            }
            byteCode = cc.toBytecode();
            cc.detach();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return byteCode;
}