Add a record to a class load with Java instrumentation

Source: Internet
Author: User
Tags arrays exit stack trace

When analyzing the cause of a program error, it is useful to understand its state of the day. In many cases, we can do this through a stack trace, but this information is often unavailable, or you may need information about the program's handling of the data in case of an error.

The traditional approach is to use a record framework such as the log4j and Java Logging APIs, and then manually write and maintain the required record statements. This is a tedious and error-prone operation and is generally suitable for automatic implementation. Java 5 added Java instrumentation mechanism allows you to examine and modify the loaded class byte code by providing a "Java proxy".

This article shows you how to implement this Java proxy, which transparently adds entry and exit records to all methods in a class with the standard Java Logging API. Take Hello world for example:

public class HelloWorld {

            public static void main(String args[]) {

                       System.out.println("Hello World");

           }

}

The following is the same use case where the entry and exit record statements are added:

import java.util.Arrays;

import java.util.logging.Level;

import java.util.logging.Logger;

public class LoggingHelloWorld {

        final static Logger _log = Logger.getLogger(LoggingHelloWorld.class.getName());

         public static void main(String args[]) {

        if (_log.isLoggable(Level.INFO)) {

        _log.info("> main(args=" + Arrays.asList(args) + ")");

        }

        System.out.println("Hello World");

        if (_log.isLoggable(Level.INFO)) {

         _log.info("< main()");

          }

     }

}

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.