Java 应用监控利器

1,354 阅读1分钟
原文链接: www.jianshu.com
  • 获取方法参数以及返回值

    业务代码:

    public String sayHello(String name, int age) {
       return "hello everyone";
    }

    BTrace代码:

    import com.sun.btrace.BTraceUtils;
    import static com.sun.btrace.BTraceUtils.*;
    import com.sun.btrace.annotations.*;
    
    @BTrace
    public class Btrace {
    
       @OnMethod(
           clazz = "com.jiuyan.message.controller.AdminController",
           method = "sayHello",
           location = @Location(Kind.RETURN)//函数返回的时候执行,如果不填,则在函数开始的时候执行
       )
       public static void sayHello(String name, int age, @Return String result) {
           println("name: " + name);
           println("age: " + age);
           println(result);
       }
    
    }

    调用sayHello('mountain', 1),输出应该是:

    name: mountain
    age: 1
    hello everyone

    可以对字符串进行正则匹配以达到监控特定问题的目的:

    if(BTraceUtils.matches(".*345.*", str)) {
        println(str);
    }
  • 计算方法运行消耗的时间

    BTrace代码:

    import java.util.Date;
    
    import com.sun.btrace.BTraceUtils;
    import static com.sun.btrace.BTraceUtils.*;
    import com.sun.btrace.annotations.*;
    
    @BTrace
    public class Btrace {
    
       @OnMethod(
           clazz = "com.jiuyan.message.controller.AdminController",
           method = "sayHello",
           location = @Location(Kind.RETURN)
       )
       public static void sayHello(@Duration long duration) {//单位是纳秒,要转为毫秒
           println(strcat("duration(ms): ", str(duration / 1000000)));
       }
    
    }