javaperf4j

Using perf4J Profiled annotation without other libraries (like log4j for example)


When using perf4J, this code works well:

StopWatch stopWatch = new LoggingStopWatch();
stopWatch.stop("example1", "custom message text");

But when using @Profiled, what to do to output or get measures, with minimum of code:

@Profiled(tag = "dynamicTag_{$0}")
public void boucle(int k)
{
    // My code to profile
}

Solution

  • When using the @Profiled annotation to add stopwatches to your code, you will typically use AspectJ Load Time Weaving (LTW) to instrument your code at load/runtime, which adds the stopwatch starts/stops and recordings around annotated methods.

    Which logging library/API (log4j, slf4j, commons-logging, JUL) is used depends on the specific instance of org.perf4j.aop.ProfiledTimingAspect you configure in your aop.xml configuring your LTW. For example this config:

    <aspectj>
      <!--
        We only want to weave in the log4j TimingAspect into the @Profiled classes.
        Note that Perf4J provides TimingAspects for the most popular Java logging
        frameworks and facades: log4j, java.util.logging, Apache Commons Logging
        and SLF4J. The TimingAspect you specify here will depend on which logging
        framework you wish to use in your code.
      -->
      <aspects>
        <aspect name="org.perf4j.log4j.aop.TimingAspect"/>
        <!-- if SLF4J/logback use org.perf4j.slf4j.aop.TimingAspect instead -->
      </aspects>
    
      <weaver options="-verbose -showWeaveInfo">
        <!--
          Here is where we specify the classes to be woven. You can specify package
          names like com.company.project.*
        -->
        <include within="ProfiledExample"/>
      </weaver>
    </aspectj>
    

    ... uses org.perf4j.log4j.aop.TimingAspect, so the stopwatches will be logged to your configured Log4J stopwatch logger. If you want to avoid third-party libraries, you can change this for the JUL JDK logger.