btrace可以对是针对java平台的一个动态追踪工具。简单点说就是可以在不停服务的情况下,对现网数据进行追踪分析和定位。最近为了定位一个jvm进程退出时java进程的运行情况,我学习了下btrace的使用。
例子:分析指定类中方法的调用和返回情况。
代码:
package com.sun.btrace.samples;
import com.sun.btrace.annotations.*;
import static com.sun.btrace.BTraceUtils.*;
/**
* A simple example that demonstrates subtype matching by +foo pattern
* in "clazz" attribute of @OnMethod annotation.
*/
@BTrace
public class YTracer {
@OnMethod(
//clazz="com.gameX.sanX.action.base.ServerChannelHandler",
//clazz="/com\\.gameX.sanX.action.base..*/",
//clazz="/com\\.gameX\\.sanX\\.action\\..*/",
//clazz="/com.gameX.gamecore.net..*/",
// clazz="/com\\.gameX.sanX.service..*/",
//clazz="/com\\.gameX\\..*/",
clazz="/com\\.gameX.sanX.service.[a-z].*/",
method="/.*/",
location=@Location(Kind.ENTRY)
)
public static void onEntryService(@ProbeClassName String pcn, @ProbeMethodName String pmn) {
print(strcat(timestamp("yyyy-MM-dd HH:mm:ss.SSS")," - ENTRY "));
print(pcn);
print('.');
println(pmn);
}
@OnMethod(
clazz="/com\\.gameX\\.sanX\\.action\\..*/",
method="/.*/",
location=@Location(Kind.ENTRY)
)
public static void onEntryAction(@ProbeClassName String pcn, @ProbeMethodName String pmn) {
print(strcat(timestamp("yyyy-MM-dd HH:mm:ss.SSS")," - ENTRY "));
print(pcn);
print('.');
println(pmn);
}
@OnMethod(
//clazz="com.gameX.sanX.action.base.ServerChannelHandler",
//clazz="/com\\.gameX.sanX.action.base..*/",
//clazz="/com\\.gameX\\.sanX\\.action\\..*/",
//clazz="/com.gameX.gamecore.net..*/",
// clazz="/com\\.gameX.sanX.service..*/",
//clazz="/com\\.gameX\\..*/",
clazz="/com\\.gameX.sanX.service.[a-z].*/",
method="/.*/",
location=@Location(Kind.RETURN)
)
public static void onReturnService(@ProbeClassName String pcn, @ProbeMethodName String pmn) {
print(strcat(timestamp("yyyy-MM-dd HH:mm:ss.SSS")," - RETURN "));
print(pcn);
print('.');
println(pmn);
}
@OnMethod(
clazz="/com\\.gameX\\.sanX\\.action\\..*/",
method="/.*/",
location=@Location(Kind.RETURN)
)
public static void onReturnAction(@ProbeClassName String pcn, @ProbeMethodName String pmn) {
print(strcat(timestamp("yyyy-MM-dd HH:mm:ss.SSS")," - RETURN "));
print(pcn);
print('.');
println(pmn);
}
}
运行举例:../bin/btrace 31976 YTracer.java
也可以把监控指令绑定到jvm的启动中
-javaagent:/home/X/btrace-1.2.3/build/btrace-agent.jar=script=./YTracer.class,scriptOutputFile=./mybtrace.log
不指定监控文件路径的话,默认会在当前进程所在路径下,文件名为btraceScript.class.btrace