本文主要介绍BTrace的使用
1.简单使用Demo
》新建一个工程,目录如下所示:
》》运行一个app程序。源码如下:
import org.apache.commons.lang3.StringUtils;
import java.util.Random;
/**
* Created by dell on 2016/12/18.
*/
public class BtraceTest
{
public static void main(String[] args)
{
String[] strs = {"", "1", "2"};
Random random = new Random();
String str;
while (true)
{
str = getStr(strs, random);
if (StringUtils.isEmpty(str))
{
System.out.println("It is impty.");
}
else
{
System.out.println("It is " + str);
}
try
{
Thread.sleep(5000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
private static String getStr(String[] strs, Random random)
{
int index = random.nextInt(strs.length);
return strs[index];
}
}
import com.sun.btrace.BTraceUtils;
import com.sun.btrace.annotations.*;
import java.util.Random;
@BTrace
public class Demo1
{
@OnMethod(clazz = "BtraceTest",method = "getStr", location = @Location(Kind.RETURN))
public static void m2(String[] strs, Random random, @Return String str)
{
BTraceUtils.println(str);
BTraceUtils.println();
BTraceUtils.println();
}
}
》》》》》运行app程序,在相同的用户下运行Btrace脚本,格式为${BTRACE_HOME}/bin/btrace app的pid Btrace脚本(Demo1.java),本实例使用如下命令执行:
zm@Inspiron:~/app/bin$ ./btrace `ps -ef |grep Btrace|grep -v grep|awk '{print $2}'` ../samples/Demo1.java
》》》》》》可以观察该函数中的返回值。
2.使用自定义的shell脚本运行Btrace脚本,来跟踪自己的类中的数据。
一般情况下,app程序引用三方jar包(非btrace jar包),并且跟踪的类时在三方包中,这时候就需要自己重新写一个shell脚本(或着修改已有的脚本)来运行btrace脚本了。
举例:跟踪Apache jar包中的StringUtils.isempty(CharSequence chars)方法。app程序和上例中的一致。btrace脚本源码(Demo.java)如下:
import com.sun.btrace.BTraceUtils;
import com.sun.btrace.annotations.BTrace;
import com.sun.btrace.annotations.Kind;
import com.sun.btrace.annotations.Location;
import com.sun.btrace.annotations.OnMethod;
@BTrace
public class Demo
{
@OnMethod(clazz = "org.apache.commons.lang3.StringUtils", method = "isEmpty", location = @Location(Kind.ENTRY))
public static void m1(java.lang.CharSequence chars)
{
BTraceUtils.println(chars);
BTraceUtils.println("");
BTraceUtils.println("");
}
}
#! /bin/sh
CUR_PATH=`pwd`
BTRACE_HOME=$(dirname "${CUR_PATH}")
#get class_path of app
for s in $(ls ${BTRACE_HOME}/build/* |grep ".jar")
do
CLASS_PATH_1=`echo $s`:${CLASS_PATH_1}
done
if [ -f "${BTRACE_HOME}/build/btrace-client.jar" ] ; then
if [ "${JAVA_HOME}" != "" ]; then
TOOLS_JAR="${JAVA_HOME}/lib/tools.jar"
${JAVA_HOME}/bin/java -cp ${CLASS_PATH_1}${TOOLS_JAR} com.sun.btrace.client.Main $*
else
echo "Please set JAVA_HOME before running this script"
exit 1
fi
else
echo "Please set BTRACE_HOME before running this script"
exit 1
fi
3.定时查看内存的脚本(每4秒打印一次),源码:
import com.sun.btrace.annotations.BTrace;
import com.sun.btrace.annotations.OnTimer;
import static com.sun.btrace.BTraceUtils.*;
@BTrace
public class TraceMemory
{
//heapUsage()/nonHeapUsage() – 打印堆/非堆内存信息,包括init、used、commit、max
@OnTimer(4000)
public static void printM()
{
//打印内存信息
println("heap:");
println(heapUsage());
println("no-heap:");
println(nonHeapUsage());
}
}