一直听说大名鼎鼎的btrace,今天抽空玩了一下,确实是现网利器!
目标:使用btrace监控tomcat中的servlet
操作系统:ubuntu-64
Jdk:jdk 1.7
Btrace:1.2.2
修改/etc/profile
1) JAVA_HOME
export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64/
export PATH=$JAVA_HOME/bin:$PATH
exportCLASSPATH=.:$JAVA_HOME/lib/rt.jar:$JAVA_HOME/lib/tools.jar
2) BTRACE_HOME
export BTRACE_HOME=/opt/app/btrace
export PATH=$BTRACE_HOME/bin:$PATH
修改catalina.sh
$JAVA_OPTS=-javaagent:btrace-agent.jar
public class HelloServlet extends HttpServlet{ private static int cnt=0; public synchronized int getCnt(){ return cnt++; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { getCnt(); String user=req.getParameter("user"); if(!checkUser(user)){ out(resp,"login failed"); return; } out(resp,"login success"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } private boolean checkUser(String user){ if(user==null||user.equals("")) return false; return true; } private void out(HttpServletResponse resp,String res) throws IOException{ OutputStream out=resp.getOutputStream(); out.write(res.getBytes()); out.flush(); out.close(); } }
TraceServlet.java
@BTrace public class TraceServlet { @TLS private static long startTime=0; //方法开始时监测cnt属性 //Kind.ENTRY @OnMethod(clazz="com.unei.servlet.HelloServlet",method="doGet",location=@Location(Kind.ENTRY)) public static void tracePropertyBefore(@Self Object self){ println(strcat("threadId:",str(threadId(currentThread())))); Field cntField=field("com.unei.servlet.HelloServlet","cnt"); Integer c=(Integer)get(cntField,self); println(strcat("start cnt:",str(c))); } /** * 方法结束时监测cnt属性 * @param @Self self this */ @OnMethod(clazz="com.unei.servlet.HelloServlet",method="doGet",location=@Location(Kind.RETURN)) public static void tracePropertyAfter(@Self Object self){ Field cntField=field("com.unei.servlet.HelloServlet","cnt"); Integer c=(Integer)get(cntField,self); println(strcat("end cnt:",str(c))); println("-----------------------"); } /** * 打印方法参数 * @ProbeClassName 类名 * @ProbeMethodName 方法名 * args 目标方法参数 */ @OnMethod(clazz="/com.unei.*/",method="/check.*/") public static void anyRead(@ProbeClassName String pcn,@ProbeMethodName String pmn,AnyType[] args){ println(strcat("method:",strcat(strcat(pcn,"."),pmn))); print("args:"); printArray(args); }