Java Instrument动态修改字节码入门-添加方法耗时监控

平常在统计方法执行的耗时时长时,一般都是在方法的开头和结尾通过System.currentTimeMillis()拿到时间,然后做差值,计算耗时,这样不得不在每个方法中都重复这样的操作,现在使用Instrument,可以优雅的实现该功能。

一、编写Agent类

package com.jdktest.instrument;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;

public class AopAgentTest {
    static private Instrumentation _inst = null;  
    /** 
     * The agent class must implement a public static premain method similar in principle to the main application entry point. 
     * After the Java Virtual Machine (JVM) has initialized, 
     * each premain method will be called in the order the agents were specified, 
     * then the real application main method will be called.
     **/  
    public static void premain(String agentArgs, Instrumentation inst) {  
        System.out.println("AopAgentTest.premain() was called.");  

        /* Provides services that allow Java programming language agents to instrument programs running on the JVM.*/  
        _inst = inst; 

        /* ClassFileTransformer : An agent provides an implementation of this interface in order to transform class files.*/  
        ClassFileTransformer trans = new AopAgentTransformer(); 

        System.out.println("Adding a AopAgentTest instance to the JVM.");  

        /*Registers the supplied transformer.*/
        _inst.addTransformer(trans);  
    }  
}

代码功能详见注释。

二、编写ClassFileTransformer

ClassFileTransformer需要实现transform方法,根据自己的功能需要修改class字节码,在修改字节码过程中需要借助javassist进行字节码编辑。

javassist是一个开源的分析、编辑和创建java字节码的类库。通过使用javassist对字节码操作可以实现动态”AOP”框架。

关于java字节码的处理,目前有很多工具,如bcel,asm(cglib只是对asm又封装了一层)。不过这些都需要直接跟虚拟机指令打交道。javassist的主要的优点,在于简单,而且快速,直接使用java编码的形式,而不需要了解虚拟机指令,就能动态改变类的结构,或者动态生成类。

package com.jdktest.instrument;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CodeConverter;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
import javassist.expr.ExprEditor;
import javassist.expr.MethodCall;

public class AopAgentTransformer implements ClassFileTransformer{

    public byte[] transform(ClassLoader loader, String className,
            Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
            byte[] classfileBuffer) throws IllegalClassFormatException {
        byte[] transformed = null;  
        System.out.println("Transforming " + className);  
        ClassPool pool = null;  
        CtClass cl = null;  
        try {  
            pool = ClassPool.getDefault();

            cl = pool.makeClass(new java.io.ByteArrayInputStream(  
                    classfileBuffer));  

//            CtMethod aop_method = pool.get("com.jdktest.instrument.AopMethods").
//                    getDeclaredMethod("aopMethod");
//            System.out.println(aop_method.getLongName());

            CodeConverter convert = new CodeConverter();

            if (cl.isInterface() == false) {  
                CtMethod[] methods = cl.getDeclaredMethods();  
                for (int i = 0; i < methods.length; i++) {  
                    if (methods[i].isEmpty() == false) {  
                        AOPInsertMethod(methods[i]);  
                    }  
                }  
                transformed = cl.toBytecode();  
            }  
        } catch (Exception e) {  
            System.err.println("Could not instrument  " + className  
                    + ",  exception : " + e.getMessage());  
        } finally {  
            if (cl != null) {  
                cl.detach();  
            }  
        }  
        return transformed;  
    }

    private void AOPInsertMethod(CtMethod method) throws NotFoundException,CannotCompileException {
        //situation 1:添加监控时间
        method.instrument(new ExprEditor() {  
            public void edit(MethodCall m) throws CannotCompileException {  
                m.replace("{ long stime = System.currentTimeMillis(); $_ = $proceed($$);System.out.println(\""
                        + m.getClassName() + "." + m.getMethodName()
                        + " cost:\" + (System.currentTimeMillis() - stime) + \" ms\");}");
            }
        }); 
        //situation 2:在方法体前后语句
//      method.insertBefore("System.out.println(\"enter method\");");
//      method.insertAfter("System.out.println(\"leave method\");");
    }

}

三、打包Agent jar包

因为agent依赖javassist,在build时需要加入<Boot-Class-Path>,pom文件如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.jdktest</groupId>
  <artifactId>MyInstrument</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>instrument</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
      <dependency>
        <groupId>javassist</groupId>
        <artifactId>javassist</artifactId>
        <version>3.8.0.GA</version>
      </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <build>  
    <plugins>  
      <plugin>  
        <groupId>org.apache.maven.plugins</groupId>  
        <artifactId>maven-jar-plugin</artifactId>  
        <version>2.2</version>  
        <configuration>  
          <archive>  
            <manifestEntries>  
              <Premain-Class>com.jdktest.instrument.AopAgentTest</Premain-Class>  
              <Boot-Class-Path>E:/maven-lib/javassist/javassist/3.8.0.GA/javassist-3.8.0.GA.jar</Boot-Class-Path>  

            </manifestEntries>  
          </archive>  
        </configuration>  
      </plugin>  

      <plugin>  
       <artifactId>maven-compiler-plugin </artifactId >  
              <configuration>  
                  <source> 1.6 </source >  
                  <target> 1.6 </target>  
              </configuration>  
     </plugin>  
    </plugins>   


  </build> 
</project>

四、需要添加耗时监控的client

随意编写需要添加耗时监控的代码并打jar包。

package com.jdktest.SayHello;

public class Target {

    public static void main(String[] args) {
        new Target().sayHello();
    }

    public void sayHello(){
        System.out.println("Hello, guys!");
    }
}

如果sayHello方法中又调用了同类中的方法或者别的类中的方法,这些被调用的方法的耗时仍可被监控到。

五、执行

在cmd下执行如下命令:

java -javaagent:E:/workspace/MyInstrument/target/MyInstrument-0.0.1-SNAPSHOT.jar -cp E:/workspace/SayHello/target/SayHello-0.0.1-SNAPSHOT.jar com.jdktest.SayHello.Target

六、执行结果

这里写图片描述

  • 0
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
opentelemetry-javaagent.jar 是一个用于自动化和 Java 应用程序的分布式跟踪的工具。我们可以使用自定义 instrument 来扩展其功能。 自定义 instrument 可以帮助我们实现一些自定义的行为,例如,我们可以在代码中插入额外的标记信息,或者在特定的函数或方法中加入额外的追踪逻辑。 要实现自定义 instrument,我们需要进行以下步骤: 1. 创建一个 Java 类,并继承 `OtelInstrumenter` 类。这是一个由 OpenTelemetry 提供的接口,用于定义自定义 instrument 的行为。 2. 在该类中,我们需要实现 `applyInstrumentation` 方法。该方法会被调用来应用自定义的 instrument 到目标应用程序中。 3. 在 `applyInstrumentation` 方法中,我们可以使用 OpenTelemetry 提供的 API 来修改目标应用程序的代码,例如,在特定的函数或方法调用前后插入追踪代码。 4. 编译并打包自定义 instrument 的代码,并将其作为 `-javaagent` 参数传递给 `opentelemetry-javaagent.jar`。当目标应用程序启动时,这个自定义 instrument 会被加载和应用。 通过使用自定义 instrument,我们可以根据自己的需求对目标应用程序的代码进行修改和增强。这样,我们就能够更好地实现跟踪和监控,并获得更加详细和准确的跟踪数据。 总结起来,opentelemetry-javaagent.jar 提供了一种灵活和可扩展的方式来实现自定义 instrument。我们可以通过创建自定义 instrument 类,并在其中实现特定的逻辑来修改目标应用程序的代码,从而实现更精确和详细的分布式跟踪。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值