Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

For the most part Java developers don’t need to be concerned with NewRelic. The server integration comes with the ability to handle Spring MVC services automatically. This is great, but what about other stuff?

I had a case where we had Spring Scheduler via Quartz firing off jobs based upon a cron schedule. These were not tracked by NewRelic, so we had to manually add them.

Maven Dependency

To add the NewRelic Java API to your project, include the following snippet.

 <dependency>
     <groupId>com.newrelic.agent.java</groupId>
     <artifactId>newrelic-api</artifactId>
     <version>3.36.0</version>
 </dependency>

Instrumenting methods

Instrumenting a call stack is very easy. Add the com.newrelic.api.agent.Trace annotation to the top of the method that you want to monitor and away you go.

@Trace(dispatcher = true)
@scheduled
public void doSomethingOnASchedule() {
    // ...
}

Error Flagging

NewRelic counts errors by counting exceptions that rise up through the instrumented methods. This works, unless your code handles the exceptions and continues on. For cases like this, you need to manually notify NewRelic that an error happened. This is handled by using the com.newrelic.api.agent.NewRelic class.

try {
    // ...
} catch (ConfigClientException ce) {
    logger.error("logging this error to the logs", e);
    NewRelic.noticeError(ce);
    // handle error without throwing
} 

The NewRelic.noticeError method has signatures that take the following data

  • Throwable
  • Throwable, Map
  • String
  • String, Map

Excluding from NewRelic instrumentation

We noticed for some applications that we had some very fast transactions that happened very regularly and the volume scaled perfectly with our servers. It turned out to be our health check system. We provide a URL to the monitoring servers that indicates if the target service is running. We did not want those to be instrumented and skew the results. This isn’t as simple as it could be, but here it goes. You need to make an annotation with a very specific name. The package doesn’t matter. I have no idea why they don’t provide this in the NewRelic API.

package com.javaninja.newrelic;


import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NewRelicIgnoreTransaction {

}

Once you have created your NewRelicIgnoreTransaction annotation, you can use it to indicate that certain timings should be excluded. An example is below:

    @NewRelicIgnoreTransaction
    @RequestMapping("/healthcheck")
    public String getInternal() {
        return "true";
    }

July 14th, 2017

Posted In: NewRelic

Leave a Reply

Your email address will not be published. Required fields are marked *

LinkedIn Auto Publish Powered By : XYZScripts.com