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.


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)
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);
    // 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;
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:

    public String getInternal() {
        return "true";

July 14th, 2017

Posted In: NewRelic


  • Jack says:

    Did you have to specify a classpath to the newrelic-api jar and if so, how did you do it?

    • sheltonn says:

      That is standard Maven functionality. Maven is managing the classpath by managing the dependencies. It then gets packaged into /WEB-INF/lib where the Tomcat classloaders will find it.

Leave a Reply

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

WP to LinkedIn Auto Publish Powered By :