Correlate your services logging with Spring Boot

In a modern service landscape, especially when using containers, you are probably using something like the ELK stack (Elasticsearch, Logstash, Kibana) to flow all the logging into.
But how to find from all those loglines what caused the nasty bug after a innocent buttonpress?
One of the easy answers to this is what’s called a correlation id – basically a unique number assigned to that buttonpress which gets carried around between the services and added to every logline.
Sounds good you say? it is so let’s see how to do this.
Continue reading

Integrate Angular in Spring Boot with Gradle

Having a Angular HTML5 single page application and a Spring Boot application, we would like to serve the complete Angular app from Spring Boot. This blog shows you a couple simple steps to get everything up and running: run NPM from Gradle, integrate the Gradle frontend build in the main build and support HTML5 mode in the ResourceHandler of Spring Boot.

Run NPM from Gradle

Create a subdirectory called frontend with the frontend code and build scripts (webpack, npm). Let’s assume our npm start and npm run watch output to the /frontend/dist/ directory.

First we need to make sure the frontend code is build when we run gradle build on our project. We can use the plugin gradle-node-plugin for this. Go ahead and create a /frontend/build.gradle file.

Now, if we run a gradle build from our frontend subdirectory:

  • node will be downloaded
  • npm install will be executed
  • npm run build will be executed

Run integrated Gradle build

To run the frontend submodule integrated from our root project, all we need to do is include a settings.gradle at the root of the project.

Go ahead and run gradle build from the root of our project and see that npm is downloaded and the expected npm tasks are run.

We need to include the distribution of the frontend build in the JAR. Thus the frontend:build task needs to be run before we process the resources of the JAR. Go ahead and add the following snippet to /build.gradle.

Support Angular HTML5 mode

Now all we need to do is create support for HTML5 mode in Angular. Angular is a single page application and subroutes of the application are default served with a ‘#’ hashtag separator. If we want to have regular paths, we can enable HTML5 mode. The problem in serving this Angular HTML5 application from Spring Boot is that the Spring Boot ResourceHandler cannot find these resources, since the real resources is the index.html with the JavaScript files. With the next code snippet we instruct Spring Boot to look for the index.html as well. This is inspired by http://stackoverflow.com/questions/24837715/spring-boot-with-angularjs-html5mode

Happy coding!