btrace示例

偷个懒,写在一个btrace脚本中了……得空再拆成多个用例

示例代码

被测试的类

package com.yl.btraceDemo.impl;

import javax.jws.WebService;

@WebService
public class DemoInfImpl {

    public int add(int firstParam, int secondParam) {
        int result =firstParam+secondParam;
        System.err.println("add result:"+result);
        return result;
    }

    public int sub(int firstParam, int secondParam) {
        int result =firstParam-secondParam;
        System.err.println("sub result:"+result);
        return result;
    }
}

测试主类如下

package com.yl.btraceDemo.main;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.yl.btraceDemo.impl.DemoInfImpl;

public class TestMain {

    private static InputStreamReader isr;

    public static void main(String[] args) {
        enterKey();
        DemoInfImpl demoInfImpl = new DemoInfImpl();
        demoInfImpl.add(1, 2);
        demoInfImpl.sub(2, -1);
        logTracer();
        testFile();
        demoInfImpl.add(1, 2);
        try {
            Thread.sleep(10*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        runtimeException();
    }

    public static void enterKey() {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        try {
            bf.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void logTracer() {
        Logger log = Logger.getLogger("com.yl.btraceDemo");
        log.setLevel(Level.INFO);
        log.info("info Level");
        log.setLevel(Level.WARNING);
        log.info("WARNING Level");
    }

    public static void runtimeException() {
        try {
            throw new RuntimeException();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }

    }

    public static void testFile() {
        File file = new File("d:\\", "addfile.txt");
        try {
            file.createNewFile(); //
        } catch (IOException e) {
            e.printStackTrace();
        }

        String str = "welcome";
        byte bt[] = new byte[1024];
        bt = str.getBytes();
        try {
            FileOutputStream in = new FileOutputStream(file);
            try {
                in.write(bt, 0, bt.length);
                in.close();
                // boolean success=true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        FileInputStream out = null;
        try {
            out = new FileInputStream(file);
            isr = new InputStreamReader(out);
            int ch = 0;
            while ((ch = isr.read()) != -1) {
                System.out.print((char) ch);
            }

        } catch (Exception e) {
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

btrace脚本如下

package com.yl.btraceDemo.scripts;

import static com.sun.btrace.BTraceUtils.classOf;
import static com.sun.btrace.BTraceUtils.concat;
import static com.sun.btrace.BTraceUtils.currentThread;
import static com.sun.btrace.BTraceUtils.field;
import static com.sun.btrace.BTraceUtils.get;
import static com.sun.btrace.BTraceUtils.jstack;
import static com.sun.btrace.BTraceUtils.printFields;
import static com.sun.btrace.BTraceUtils.printNumberMap;
import static com.sun.btrace.BTraceUtils.println;
import static com.sun.btrace.BTraceUtils.runFinalization;
import static com.sun.btrace.BTraceUtils.str;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

import com.sun.btrace.BTraceUtils.Atomic;
import com.sun.btrace.BTraceUtils.Collections;
import com.sun.btrace.BTraceUtils.Reflective;
import com.sun.btrace.BTraceUtils.Strings;
import com.sun.btrace.BTraceUtils.Threads;
import com.sun.btrace.annotations.BTrace;
import com.sun.btrace.annotations.Duration;
import com.sun.btrace.annotations.Kind;
import com.sun.btrace.annotations.Location;
import com.sun.btrace.annotations.OnMethod;
import com.sun.btrace.annotations.OnTimer;
import com.sun.btrace.annotations.ProbeClassName;
import com.sun.btrace.annotations.ProbeMethodName;
import com.sun.btrace.annotations.Self;
import com.sun.btrace.annotations.TLS;

@BTrace(unsafe = true)
public class TestOnMethod {
    // line设置为-1会打印所有行
    // 演示@OnMethod 、正则匹配、@Location、@ProbeClassName、@ProbeMethodName
    @OnMethod(clazz = "com.yl.btraceDemo.impl.DemoInfImpl", method = "/.*/", location = @Location(value = Kind.LINE, line = 10))
    public static void online(@ProbeClassName String pcn, @ProbeMethodName String pmn, int line) {
        println("[online]:" + pcn + "." + pmn + ":" + line);
    }

    @OnMethod(clazz = "/com\\.yl\\.btraceDemo\\.impl..*/", location = @Location(value = Kind.LINE, line = 16))
    public static void onlineMatch(@ProbeClassName String pcn, @ProbeMethodName String pmn, int line) {
        println("[onlineMatch]:" + pcn + "." + pmn + ":" + line);
    }

    // 演示基于注解匹配、@Location、@Duration
    @OnMethod(clazz = "@javax.jws.WebService", location = @Location(Kind.RETURN))
    public static void onWebserviceReturn(@ProbeClassName String pcn, @ProbeMethodName String pmn, @Duration long d) {
        println("[onWebserviceReturn]:"+Strings.strcat(Strings.strcat(pcn, "."), pmn));
        println("[onWebserviceReturn]:"+Strings.strcat("Time taken (msec) ", Strings.str(d / 1000)));
    }

    // 演示@Self
    private static Field msgField = Reflective.field("java.util.logging.LogRecord", "message");

    @OnMethod(clazz = "+java.util.logging.Logger", method = "log")
    public static void onLog(@Self Logger self, LogRecord record) {
        println("[onLog]:"+Reflective.get(msgField, record));
    }

    // 演示Throw相关
    @TLS
    static Throwable currentException;

    @OnMethod(clazz = "java.lang.Throwable", method = "<init>")
    public static void onthrowFirst(@Self Throwable self, String s) {
        currentException = self;
    }

    @OnMethod(clazz = "java.lang.Throwable", method = "<init>")
    public static void onthrowSecond(@Self Throwable self, String s, Throwable cause) {
        currentException = self;
    }

    @OnMethod(clazz = "java.lang.Throwable", method = "<init>")
    public static void onthrowThird(@Self Throwable self, Throwable cause) {
        currentException = self;
    }

    // when any constructor of java.lang.Throwable returns
    // print the currentException's stack trace.
    @OnMethod(clazz = "java.lang.Throwable", method = "<init>", location = @Location(Kind.RETURN))
    public static void onthrowreturn() {
        if (currentException != null) {
            Threads.jstack(currentException);
            currentException = null;
        }
    }

    // FileTracker
    @TLS
    private static String name;

    @OnMethod(clazz = "java.io.FileInputStream", method = "<init>")
    public static void onNewFileInputStream(@Self FileInputStream self, File f) {
        name = Strings.str(f);
    }

    @OnMethod(clazz = "java.io.FileInputStream", method = "<init>", type = "void (java.io.File)", location = @Location(Kind.RETURN))
    public static void onNewFileInputStreamReturn() {
        if (name != null) {
            println("[onNewFileInputStreamReturn]:opened for read " + name);
            name = null;
        }
    }

    @OnMethod(clazz = "java.io.FileOutputStream", method = "<init>")
    public static void onNewFileOutputStream(@Self FileOutputStream self, File f, boolean b) {
        name = str(f);
    }

    // 演示OnMethod tpye
    @OnMethod(clazz = "java.io.FileOutputStream", method = "<init>", type = "void (java.io.File, boolean)", location = @Location(Kind.RETURN))
    public static void OnNewFileOutputStreamReturn() {
        if (name != null) {
            println("[OnNewFileOutputStreamReturn]:opened for write " + name);
            name = null;
        }
    }

    private static Field fdField = field("java.io.FileInputStream", "fd");

    // 演示ontimer
    @OnTimer(100)
    public static void ontimer() {
        runFinalization();
    }

    @OnMethod(clazz = "java.io.FileInputStream", method = "finalize")
    public static void onfinalize(@Self Object me) {
        println("[onfinalize]:"+concat("finalizing ", str(me)));
        printFields("[onfinalize]:"+me);
        printFields("[onfinalize]:"+get(fdField, me));
    }

    @OnMethod(clazz = "java.io.FileInputStream", method = "close")
    public static void onclose(@Self Object me) {
        println("[onclose]:"+concat("closing ", str(me)));
        println("[onclose]:"+concat("thread: ", str(currentThread())));
        printFields("[onclose]:"+me);
        printFields("[onclose]:"+get(fdField, me));
        jstack();
    }


    //Histogram
    private static Map<String, AtomicInteger> histo = Collections.newHashMap();
    @OnMethod(clazz = "com.yl.btraceDemo.impl.DemoInfImpl", method = "add")
    public static void onnewObject(@Self Object obj) {
        String cn = Reflective.name(classOf(obj));
        AtomicInteger ai = Collections.get(histo, cn);
        if (ai == null) {
            ai = Atomic.newAtomicInteger(1);
            Collections.put(histo, cn, ai);
        } else {
            Atomic.incrementAndGet(ai);
        }
    }

    @OnTimer(4000)
    public static void printHisto() {
        if (Collections.size(histo) != 0) {
            printNumberMap("[printHisto]:"+"Component Histogram", histo);
        }
    }

}

运行(本例在windows下运行)

运行测试主类
启动控制台,jps查询pid
btrace -u pid $path\TestOnMethod.java
在运行的主类按任意键继续运行

d:\M4etcd\btraceDemo\src\com\yl\btraceDemo\scripts>jps
54772
41064 TestMain
57432 Jps

d:\M4etcd\btraceDemo\src\com\yl\btraceDemo\scripts>btrace -u 41064 TestOnMethod.java
[onfinalize]:finalizing java.io.FileInputStream@7cdbacbe
{value=[C@7623c7ce, hash=0, }
{value=[C@123ea3e8, hash=0, }
[onclose]:closing java.io.FileInputStream@7cdbacbe
[onclose]:thread: Thread[Finalizer,8,system]
{value=[C@2d8a20f, hash=0, }
{value=[C@6a2d082d, hash=0, }
java.io.FileInputStream.close(FileInputStream.java)
java.io.FileInputStream.finalize(FileInputStream.java:397)
java.lang.System$2.invokeFinalize(System.java:1270)
java.lang.ref.Finalizer.runFinalizer(Finalizer.java:98)
java.lang.ref.Finalizer.access$100(Finalizer.java:34)
……

例子里面写的比较多,运行时,可以只关注部分,注释其他 这样信息就比较容易分辨
比如只保留

@BTrace(unsafe = true)
public class TestOnMethod {
    // line设置为-1会打印所有行
    // 演示@OnMethod 、正则匹配、@Location、@ProbeClassName、@ProbeMethodName
    @OnMethod(clazz = "com.yl.btraceDemo.impl.DemoInfImpl", method = "/.*/", location = @Location(value = Kind.LINE, line = 10))
    public static void online(@ProbeClassName String pcn, @ProbeMethodName String pmn, int line) {
        println("[online]:" + pcn + "." + pmn + ":" + line);
    }
    @OnMethod(clazz = "/com\\.yl\\.btraceDemo\\.impl..*/", location = @Location(value = Kind.LINE, line = 16))
    public static void onlineMatch(@ProbeClassName String pcn, @ProbeMethodName String pmn, int line) {
        println("[onlineMatch]:" + pcn + "." + pmn + ":" + line);
    }
}

例子的输出信息就简单很多~ 同理可以注释其他的注入

d:\M4etcd\btraceDemo\src\com\yl\btraceDemo\scripts>jps
53408 Jps
54772
9524 TestMain

d:\M4etcd\btraceDemo\src\com\yl\btraceDemo\scripts>btrace -u 9524 TestOnMethod.java
[online]:com.yl.btraceDemo.impl.DemoInfImpl.add:10
[onlineMatch]:com.yl.btraceDemo.impl.DemoInfImpl.sub:16
[online]:com.yl.btraceDemo.impl.DemoInfImpl.add:10

d:\M4etcd\btraceDemo\src\com\yl\btraceDemo\scripts>

btrace用户手册1.3.9
btrace注解
btrace示例

原文连接 http://blog.csdn.net/yue530tomtom/article/details/78713395

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值