Kind.ENTRY 入口,默认值
Kind.RETURN: 返回
Kind.THROW: 异常
Kind.Line: 行
一、返回时拦截
package com.example.monitor_tuning.chapter4; import com.sun.btrace.AnyType;
import com.sun.btrace.BTraceUtils;
import com.sun.btrace.annotations.*; @BTrace
public class PrintReturn { @OnMethod(
clazz = "com.example.monitor_tuning.chapter4.Ch4Controller",
method="arg1",
location = @Location(Kind.RETURN)
)
public static void anyRead(@ProbeClassName String pcn, @ProbeMethodName String pmn, @Return AnyType result)
{
BTraceUtils.println(pcn + "," + pmn + "," + result);
BTraceUtils.println();
}
}
2、运行和返回结果
1)、运行
2)、调用接口:
http://127.0.0.1:8080/monitor_tuning/ch4/arg1?name=nick
3)返回结果见上图
二、异常时拦截
1、创建异常代码
2、创建异常脚本
package com.example.monitor_tuning.chapter4; import com.sun.btrace.BTraceUtils;
import com.sun.btrace.annotations.*; /**
* 拦截异常
*/
@BTrace
public class PrintOnThrow { @TLS
static Throwable currentException; @OnMethod(
clazz = "java.lang.Throwable",
method="<init>"
)
//拦截 new Throwable
public static void onthrow(@Self Throwable self)
{
currentException = self;
} @OnMethod(
clazz = "java.lang.Throwable",
method="<init>"
)
//拦截 new Throwable(String msg)
public static void onthrow1(@Self Throwable self, String s)
{
currentException = self;
} @OnMethod(
clazz = "java.lang.Throwable",
method="<init>"
)
//拦截 new Throwable(Throwable self, String s, Throwable cause)
public static void onthrow1(@Self Throwable self, String s, Throwable cause)
{
currentException = self;
} @OnMethod(
clazz = "java.lang.Throwable",
method="<init>"
)
//拦截 new Throwable( Throwable self, Throwable cause)
public static void onthrow2(@Self Throwable self, Throwable cause)
{
currentException = self;
} @OnMethod(
clazz = "java.lang.Throwable",
method="<init>",
location = @Location(Kind.RETURN)
)
public static void onthrowreturn()
{
if(currentException != null){
BTraceUtils.Threads.jstack(currentException); //打印异常堆栈
BTraceUtils.println("==============");
currentException = null;
}
} }
3、运行btrace脚本
调用接口
http://127.0.0.1:8080/monitor_tuning/ch4/exception
显示结果
三、打印行号
1、打印36行是否执行
2、创建btrace脚本
package com.example.monitor_tuning.chapter4; import com.sun.btrace.BTraceUtils;
import com.sun.btrace.annotations.*; /**
* 打印行号,查看指定行号是否执行到
*/
@BTrace
public class PrintLine { @OnMethod(
clazz = "com.example.monitor_tuning.chapter4.Ch4Controller",
location = @Location(value = Kind.LINE, line = 36)
) public static void anyRead(@ProbeClassName String pcn, @ProbeMethodName String pmn, int line)
{
BTraceUtils.println(pcn + "," + pmn + ", " + line);
BTraceUtils.println();
}
}
3、执行
调用接口
http://localhost:8080/monitor_tuning/ch4/exception
显示结果
4、打印所有执行的行号
1)接口对应的行号
2、修改btrace脚本 line为-1
显示结果
说明 36, 37, 39, 42行被执行了。38行没有被执行到。