Btrace Introduction and instructions for use

Source: Internet
Author: User
Tags statsd

Everyone in the development process will always notice a variety of bugs, not when you can go to debug, and not when you can go to add the required log in the code, this time how to solve it? This is the time to Btrace, the following through the introduction of Btrace , and there are some sample code that hopefully will give you some insight.

Brief introduction

Btrace (Byte Trace) is a Java dynamic, security tracking tool introduced by sun to monitor the online situation without downtime, and to minimize intrusion and minimize system resources. Btrace application of the broader reason should be its security and non-invasive, wherein the thermal interaction technology, so that we do not need to launch agent dynamic tracking analysis, its security does not lead to any destructive impact on the target Java process, making btrace a tool for our online product problem positioning. No intrusion, no need to make any changes to the original code, reduce the risk of on-line and test costs, and no need to restart the target Java process for the agent to dynamically analyze and track the target program, it can be said that Btrace can meet most of the application scenarios.

Install Download Btrace

Btrace has migrated to GitHub, the latest version is v1.3.11 download Github.com/btraceio/btrace/releases/download/v1.3.11/btrace-bin-1.3.11.zip After extracting to the specified directory

Configure Btrace_home
VI. bash_profile
java_home=/library/java/javavirtualmachines/jdk1.8.0_45.jdk/contents/homebtrace_home=/users/david/downloads/ Btrace-bin-1.3.11path= $PATH: $BTRACE _home/bin: $JAVA _home/bin: $HOME/binexport java_homeexport Btrace_homeexport PATH

Executes the source after the configuration is complete. Bash_profile

Enter Btrace in the terminal to see the following:

$ btraceusage:btrace <options> <pid> <btrace source or. class file                    > <btrace arguments>where possible options include:--version Show the Version-v Run in verbose mode-o <file> the path to store the probe output (would disable showing the output in Console)-U Run in trusted mode-d <path> Dump the instrumented classes to the SPECIF IED PATH-PD <path> The search path for the probe XML Descriptors-classpath <path> Specify W Here to find the user class files and annotation processors-cp <path> specify where to find user class file             s and annotation processors-i <path> specify where to find include Files-p <port> Specify port to which the Btrace agent listens for CLIENTS-STATSD 

  

Btrace use
    1. JPS command to isolate the JVM PID to monitor
    2. Writing the Btrace Tracker
    3. Execution: Btrace <pid> btrace Tracker
Precautions

The Btrace script is an ordinary Java class annotated with @btrace that contains one or more public static void-modified methods, noting that the interception method must be decorated with public static void, if not a static method throws Instance methods is not allowed such exception information will prompt Btrace methods should if it is not public; if there is a return, the prompt is: Btrace probe methods Must return void

To ensure that the target program is not affected, the Btrace script makes a number of restrictions on the actions it can perform, as follows:

    1. Cannot create object
    2. Cannot throw or catch exceptions
    3. Can't use synchronized keyword
    4. Instace or static variables in the target program cannot be
    5. Cannot invoke the instance or static method of the target program
    6. The field and method of the script must be static
    7. Scripts cannot include outer,inner,nested class
    8. The script cannot have loops, cannot inherit any class, any interface with ASSERT statement
Btrace annotations

For BTrace learning is inseparable from the understanding of BTrace annotations, BTrace annotations can be divided into class annotations @BTrace method annotations such as @onmethod parameter annotations such as: @ProbeClassName in order to better understand the demo later we begin with the parameter annotations

 @ProbeClassName

The parameter used to mark the processing method, only the user @onmethod, and the value of the parameter is the class name being traced

@ProbeMethodName

Parameters used for cousin processing methods, only the user @OnMethod, the parameter value is the name of the tracked method

@Self

Enclosing instance parameters of the current interception method

@Return

The return value of the current intercept method, only valid for location= @Location (Kind.return)

@Duration

Execution time of the current interception method

@ TargetInstance

An instance of an internal invocation of the current intercept method

@TargetMethodOrField

The method name that is called internally by the current intercept method

Method annotations Focus on Onmethod This is also our focus when troubleshooting problems.

@OnMethod role

Used to specify the tracking method to the target class, the target method, and the target location

Format

@OnMethod (clazz=<cname_spec>[, Method=<mname_spec>]? [, Type=<signature>]? [, Location=<location_spec>]?)

Parameter description Clazz used to qualify the target class

Cname_spec = <class_name> | +<class_name> | /regex/class_name is the fully qualified class name +class_name the fully qualified class name preceded by "+" to denote all subclasses or implementations of the class,/regex/is the standard regular expression for the user to identify the class name

Method user-defined target methods, Mname_spec represents a simple method name, does not include the signature and return type;

Type: The signature and return type of the user-qualified target method <return_type> ((Arg_type (, arg_type) *)? Return_type is the return type of the method, such as void, java.lang.String; Arg_type is the parameter type

Location is used to define the position of the target method, specified by the @location annotation

@Location properties are:

    1. Value defaults to Kind.entry that is the entry position of the parameter
    2. The Where-qualified probe location defaults to Where.before and can also be set to Where.after
    3. Clazz
    4. Method
    5. Field
    6. Type
    7. Line

Where the values of @Kind annotations are

    • Kind.entry-by trace Method parameter
    • Kind.return-The Trace method returns a value
    • Kind.throw-Throwing Exceptions
    • Kind.array_set, Kind.array_get-array index
    • Kind.catch-catch exception
    • Kind.field_set-Attribute value
    • Kind.line-line number
    • Kind.new-Class name
    • Kind.error-Throwing Exceptions

Gets the Intercept method class, method, instance, return value, and time-consuming information, the qualified class is the implementation class of the map interface, the method is before the put position is return

@BTracepublic class Tracingscript {@OnMethod (clazz= "+java.util.map", method= "put", location= @Location (Kind.return)) Public  static void Testb (@ProbeClassName string pcm, @ProbeMethodName string PMN, @Self the Object self, @Duration long dur ation, @Return  Object result) {          println (strcat (strcat (strcat (PCM, "#"), strcat), "PMN in"), str (self)) ;           println (strcat (strcat ("result is", str (result), strcat ("duration is", str (duration))))      

The result of the output is:

Java.util.hashmap#put called IN{NAME=JAVAX.MANAGEMENT.OBJECTNAME$PROPERTY@338BF6B2, type= Javax.management.objectname$property@6f24f3ca}result is null duration is 2488java.util.hashmap#put called in{ Javax.management.objectname=java.lang.object@74685cec}result is null duration is 5692java.util.hashmap#put called in{ Type=javax.management.objectname$property@582e822b}result is null duration is 2957java.util.hashmap#put called in{ name=javax.management.objectname$property@10dc9047, Type=javax.management.objectname$property@582e822b}result is Null duration is 2683

Get the Intercept method internal call instance and method

@OnMethod (clazz= "+java.util.map", method= "get", location= @Location (Value=kind.call, clazz= "/.*/", method= "/.*/")) Public      static void TestA (@ProbeClassName string pcm, @TargetInstance Object target, @TargetMethodOrField string Fiel d) {                println (strcat ("Target is", strcat (strcat (str (target), "#"), field)));          

The result of the output is:

Target Isjava.io.objectstreamclass$weakclasskey@3952cb51#hashcodetarget isjava.io.objectstreamclass$ Weakclasskey@3952cb51#equals

  

@OnTimer

Used to specify that the trace operation is timed. Value is used to specify the time interval

Import Com.sun.btrace.annotations.*;import static Com.sun.btrace.btraceutils.*;import Java.util.map;import Java.util.concurrent.atomic.AtomicInteger; @BTracepublic class Tracingscript {private static map<string,    atomicinteger> histo = Collections.newhashmap (); @OnMethod (clazz = "+java.util.map", method = "Put", location = @Location (value = kind.return, Clazz = "/.*/", method = "/.") */") public static void Testb (@ProbeClassName string pcm, @ProbeMethodName string PMN, @Self the Object self, @Duration lo        ng duration, @Return Object result) {String cn = Reflective.name (Classof (self));        Atomicinteger ai = collections.get (Histo, CN);            if (AI = = null) {AI = Atomic.newatomicinteger (1);        Collections.put (Histo, CN, AI);        } else {atomic.incrementandget (AI); }} @OnTimer (+) public static void print () {if (Collections.size (histo)! = 0) {Printnumber        Map ("Component histogram", histo); }   }} 

The result of the output is:

* Component Histogram *java.util.hashmap = 130

  

@OnError

When the trace code throws an exception or an error, the method of the annotation is executed. If other methods in the same trace script throw an exception, the annotation method is also executed.

@OnEvent

Triggered by Btrace client events, the following code can be triggered by sending an event in JVISUALVM

@OnEvent public    static void Printevent () {        if (collections.size (histo)!=0) {                Printnumbermap ("Component Histogram ", histo);             }        }

  

* Component Histogram *java.util.hashmap = 131

  

Using Btrace in JVISUALVM

First select tools, plug-in installation Btrace plug-in

Select the project you want to track,

Btraceutils Method Introduction
    • Gets the current thread btraceutils.currentthread ()
    • Gets the current thread name BTraceUtis.Threads.name (Btraceutils.currentthread ())
    • Print Current thread Jstack BTraceUtils.Threads.jstack ()
    • Get current time timestamp ()
    • Gets the current time millisecond value Millis ()
    • Create StringBuilder Newstringbuilder ()
    • Append string Append ()
         Appendable Builder=strings.newstringbuilder ();         Strings.append (builder, "Current time:");         Strings.append (Builder,timestamp ());         
    • String Stitching strcat ("str1", "str2") concat ("str1", "str2")
    • string comparison strcmp ("str1", "str2")
    • Intercept string substr ("str", 0, 1)
    • Gets the string length strlen ("str")
    • Whether the string matches the specified regular expression matches (regex, input)
    • Converts an object to a string str ()




    •   

  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.