New Relic for Spring Boot - spring

Recently, we convert a tomcat/spring app to spring boot. Everything is working fine apart from new relic. Is there a way I can easily config new relic with spring boot project. I don't want to hard code the location of new relic agent jar path, then run the spring boot project with the path.
edit: Spring boot project is with maven

You can include NewRelic Maven dependency and use maven-dependency-plugin to unpack in into your target/classes directory, which allows Maven to include it into final Jar file. Then you have to add Premain-Class attribute into manifest file and you can use your application jar as -javaagent source. You can find details on my blog post

Step by step instructions
Extract the files from the newrelic java agent archive.
Create a directory named newrelic in the root of your application.
Place the newrelic.jar from the archive in the above created newrelic folder
Place the newrelic.yml YAML config file in the above created newrelic folder.
Update the values in newrelic.yml as below.
license_key: 'your license key'
app_name: ‘Your application name’
Run you application by using the option javaagent
java -javaagent:newrelic\newrelic.jar -jar yourapplication.jar
-javaagent option needs to be before the -jar so the agent can start

I was stuck with the same issue, here is what I figured out. I implemented the 2nd way for my applications.
There are 3 ways to integrate New Relic with a Spring Boot Application-
Using the Java Agent provided by New Relic
Using New Relic's Micrometer Dependency
Micormeter's New Relic Dependency
1. Configuration using Java Agent Provided By New Relic
Download the Java Agent from this URL- https://docs.newrelic.com/docs/release-notes/agent-release-notes/java-release-notes/
Extract it.
Modify the newrelic.yml file inside the extracted folder to include your
license_key:
app_name:
Create a SpringBoot application with some REST endpoints.
Build the application.
Navigate to the root path where you have extracted the newrelic java agent.
Enter this command
java -javagent:<path to your new relic jar>\newrelic.jar -jar <path to your application jar>\<you rapplication jar name>.jar
To view the application metrics-
Log in to your New Relic account.
Go to Explorer Tab.
Click on Services-APM
You can see the name of your application(which you had mentioned in the newrelic.yml file) listed there.
Click on the application name.
The dashboard should look something like this.
Using New Relic's Micrometer Dependency is the preferred way to do it.
2. Configuration using New Relic's Micrometer Dependency
Add this dependency
<dependency>
<groupId>com.newrelic.telemetry</groupId>
<artifactId>micrometer-registry-new-relic</artifactId>
<version>0.7.0</version>
</dependency>
Modify the MicrometerConfig.java class to add your API Key and Application name.
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.springframework.boot.actuate.autoconfigure.metrics.CompositeMeterRegistryAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.metrics.MetricsAutoConfiguration;
import org.springframework.boot.actuate.autoconfigure.metrics.export.simple.SimpleMetricsExportAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.newrelic.telemetry.Attributes;
import com.newrelic.telemetry.micrometer.NewRelicRegistry;
import com.newrelic.telemetry.micrometer.NewRelicRegistryConfig;
import java.time.Duration;
import io.micrometer.core.instrument.config.MeterFilter;
import io.micrometer.core.instrument.util.NamedThreadFactory;
#Configuration
#AutoConfigureBefore({ CompositeMeterRegistryAutoConfiguration.class, SimpleMetricsExportAutoConfiguration.class })
#AutoConfigureAfter(MetricsAutoConfiguration.class)
#ConditionalOnClass(NewRelicRegistry.class)
public class MicrometerConfig {
#Bean
public NewRelicRegistryConfig newRelicConfig() {
return new NewRelicRegistryConfig() {
#Override
public String get(String key) {
return null;
}
#Override
public String apiKey() {
return "your_api_key"; // for production purposes take it from config file
}
#Override
public Duration step() {
return Duration.ofSeconds(5);
}
#Override
public String serviceName() {
return "your_service_name"; // take it from config file
}
};
}
#Bean
public NewRelicRegistry newRelicMeterRegistry(NewRelicRegistryConfig config) throws UnknownHostException {
NewRelicRegistry newRelicRegistry = NewRelicRegistry.builder(config)
.commonAttributes(new Attributes().put("host", InetAddress.getLocalHost().getHostName())).build();
newRelicRegistry.config().meterFilter(MeterFilter.ignoreTags("plz_ignore_me"));
newRelicRegistry.config().meterFilter(MeterFilter.denyNameStartsWith("jvm.threads"));
newRelicRegistry.start(new NamedThreadFactory("newrelic.micrometer.registry"));
return newRelicRegistry;
}
}
Run the application.
To view the Application metrics-
Log in to your New Relic account.
Go to Explorer Tab.
Click on Services-OpenTelemetry
You can see the name of your application(which you had mentioned in the MicrometerConfig file) listed there.
Click on the application name.
The dashboard should look something like this.
Here is the link to my original question.

Related

Spring Boot Application - Running jar file gives ResourceFinderException error

Created a jar file for a spring boot multimodule application and ran the jar file using java -jar command. While starting the application, it gives ResourceFinderException. When I analyzed it, the issue is happening because in my ResourceConfig file, i have used the package for my api end points. If I use register(service.class), the application starts fine. Any suggestion how can I provide the package instead of using register? The reason I want to use package is because I have lots of services inside multiple packages and the code looks very ugly if i use register for all the services. The ResourceConfig file looks like below.
public class AppResourceConfig extends ResourceConfig {
public AppResourceConfig {}{
super();
property("jersery.config.beanValidation.enableOutputValidationErrorEntity.server");
**packages("com.api");**
register(GsonProvider.class);
register(RequestContextFilter.class);
register(NotFoundExceptionMapper.class);
register(DefaultExceptionMapper.class);
}
}
Here the issue is with highlighted line: packages("com.api")
If I comment out this code application will be up. Otherwise it is giving org.glassfish.jersey.server.internal.scanning.ResourceFinderException: java.io.FileNotFoundException: api-01.03.00.04-snapshot.jar (No such file or direcotry)
Note: api-01.03.00.04-snapshot.jar is the jar file for one of the module in a project

Unable to start Jetty Server - Error scanning entry META-INF/versions/9/

When running XACML-PAP-ADMIN and XACML-PAP-REST on Windows 10. Java jdk1.8.0_144. I get next error:
Error scanning entry META-INF/versions/9/module-info.class from jar file:///D:/Projects/XACML/XACML-PAP-ADMIN/target/xacml-pap-admin-2.0.0-SNAPSHOT/WEB-INF/lib/log4j-api-2.11.0.jar
That could be linked to your version of Jetty, considering it fails on log4j 2.11 jar.
See this question:
log4j 2.9 and later are multi-release jars for Java 9.
Make sure to use a Jetty compatible with that, or use slf4j instead.
You can create a custom DevMode JettyLauncher:
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.dev.shell.jetty.JettyLauncher;
import org.eclipse.jetty.webapp.WebAppContext;
import java.io.File;
public class DevModeJettyLauncher extends JettyLauncher {
#Override
protected WebAppContext createWebAppContext(TreeLogger logger, File appRootDir) {
WebAppContext webAppContext = super.createWebAppContext(logger, appRootDir);
webAppContext.setAttribute("org.eclipse.jetty.server.webapp.WebInfIncludeJarPattern", "none");//this is just a regex that matches nothing
return webAppContext;
}
}
And then configure it when launching.
Dev Mode Parameters: -server <package>.DevModeJettyLauncher

Spring boot on Tomcat with external configuration

I can't find an answer to this question on stackoverflow hence im asking here so I could get some ideas.
I have a Spring Boot application that I have deployed as a war package on Tomcat 8. I followed this guide Create a deployable war file which seems to work just fine.
However the issue I am currently having is being able to externalize the configuration so I can manage the configuration as puppet templates.
In the project what I have is,
src/main/resources
-- config/application.yml
-- config/application.dev.yml
-- config/application.prod.yml
-- logback-spring.yml
So how can I possibly load config/application.dev.yml and config/application.prod.yml externally and still keep config/application.yml ? (contains default properties including spring.application.name)
I have read that the configuration is load in this order,
A /config subdirectory of the current directory.
The current directory
A classpath /config package
The classpath root
Hence I tried to load the configuration files from /opt/apache-tomcat/lib to no avail.
What worked so far
Loading via export CATALINA_OPTS="-Dspring.config.location=/opt/apache-tomcat/lib/application.dev.yml"
however what I would like to know is,
Find out why loading via /opt/apache-tomcat/lib classpath doesn't work.
And is there a better method to achieve this ?
You are correct about load order. According to Spring boot documentation
SpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment:
A /config subdirectory of the current directory.
The current directory
A classpath /config package
The classpath root
The list is ordered by precedence (properties defined in locations higher in the list override those defined in lower locations).
[Note]
You can also use YAML ('.yml') files as an alternative to '.properties'.
This means that if you place your application.yml file to /opt/apache-tomcat/lib or /opt/apache-tomcat/lib/config it will get loaded.
Find out why loading via /opt/apache-tomcat/lib classpath doesn't work.
However, if you place application.dev.yml to that path, it will not be loaded because application.dev.yml is not filename Spring is looking for. If you want Spring to read that file as well, you need to give it as option
--spring.config.name=application.dev or -Dspring.config.name=application.dev.
But I do not suggest this method.
And is there a better method to achieve this ?
Yes. Use Spring profile-specific properties. You can rename your files from application.dev.yml to application-dev.yml, and give -Dspring.profiles.active=dev option. Spring will read both application-dev.yml and application.yml files, and profile specific configuration will overwrite default configuration.
I would suggest adding -Dspring.profiles.active=dev (or prod) to CATALINA_OPTS on each corresponding server/tomcat instance.
I have finally simplified solution for reading custom properties from external location i.e outside of the spring boot project. Please refer to below steps.
Note: This Solution created and executed windows.Few commands and folders naming convention may vary if you are deploying application on other operating system like Linux..etc.
1. Create a folder in suitable drive.
eg: D:/boot-ext-config
2. Create a .properties file in above created folder with relevant property key/values and name it as you wish.I created dev.properties for testing purpose.
eg :D:/boot-ext-config/dev.properties
sample values:
dev.hostname=www.example.com
3. Create a java class in your application as below
------------------------------------------------------
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
#PropertySource("classpath:dev.properties")
#ConfigurationProperties("dev")
public class ConfigProperties {
private String hostname;
//setters and getters
}
--------------------------------------------
4. Add #EnableConfigurationProperties(ConfigProperties.class) to SpringBootApplication as below
--------------------------------------------
#SpringBootApplication
#EnableConfigurationProperties(ConfigProperties.class)
public class RestClientApplication {
public static void main(String[] args) {
SpringApplication.run(RestClientApplication.class, args);
}
}
---------------------------------------------------------
5. In Controller classes we can inject the instance using #Autowired and fetch properties
#Autowired
private ConfigProperties configProperties;
and access properties using getter method
System.out.println("**********hostName******+configProperties.getHostName());
Build your spring boot maven project and run the below command to start application.
-> set SPRING_CONFIG_LOCATION=<path to your properties file>
->java -jar app-name.jar

Spring Boot - deploy .properties file to a folder different than 'WEB-INF/classes'

I'm trying to convert a traditional Tomcat Spring MVC webapp to Spring Boot. The new application should still use .war deployment.
For various reasons I have the obligatory requirement that the application.properties file resides inside a WEB-INF/conf folder in the deployed app and NOT inside the WEB-INF/classes folder where Spring Boot puts it by default.
In the original webapp I could put the application.properties file inside the src/main/webapp/WEB-INF/conf folder (so they get copied to WEB-INF/conf in the deployed application) and then use it like this:
<context:property-placeholder location="/WEB-INF/conf/application.properties"/>
What is the Spring Boot way to refer to this location?
I tried adding each of the following:
spring.config.location=WEB-INF/conf/application.properties
but my application.properties file still doesn't get loaded.
What finally worked was the following #PropertySource annotation.
#SpringBootApplication
#PropertySource(value = {"WEB-INF/conf/application.properties"})
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
It seems that not specifying classpath: or file: at the beginning of a path makes it use a path relative to the webapp.
I'm still not sure as to why specifying
spring.config.location=WEB-INF/conf/application.properties
didn't have the same effect.

Unable to import Spring Security #Secured Annotation into Grails 3

I am currently following the Spring Security 3.0.0.M1 plugin tutorial for Grails here and I appear to be stuck on Step 8. Using the statement import grails.plugin.springsecurity.annotation.Secured does not work because Grails cannot resolve the package name. I know that Spring Security for Grails 3 is in its infancy, but has anyone been able to get past this step yet? For reference, here is my SecureController class (with a another import that also does not work):
package ldaptest.controllers
import grails.plugin.springsecurity.annotation.Secured;
import org.springframework.security.access.annotation.Secured;
#Secured('ROLE_ADMIN')
class SecureController {
def index() {
render 'Secure access only'
}
}
I may found a solution:
Create a "lib" folder e.g. inside your "grails-app" directory.
Download the SpringSecurityCore JAR from here and move it into the lib directory
Add gradle dependency:
compile files('lib/spring-security-core-3.0.0.M1.jar')
Hope this helps.
Greetings
I had:3,1,1 the save problem with my application. I solved it by adding as a library to my project. However I had to change import package to make it work.
import org.springframework.security.access.annotation.Secured
I am using IntelliJ IDEA, I just has to search the maven repo for the spring-security-core:3.1.1.
In IntelliJ you do : File > Project Structure > Libraries > Add > From Maven Repository. Then do the search according to the version of "spring-security-core" you want to use.

Resources