Spring Boot Google Cloud Logging example

In this section, we will deploy a Spring Boot application in Google Cloud App Engine, and we will introduce how to write logs to Google Cloud Logging and how to check the logs in the Logs Explorer.


1. Creating a simple spring boot web application

First, open the Spring initializr https://start.spring.io/ 

Then, Provide the Group and Artifact name. We have provided Group name com.knf.dev.demo and Artifact spring-boot-gcp-logging-example. Here I selected the Maven project - language Java 11 - Spring Boot 2.7.9 and add Spring web dependency, and GCP Support.

Then, click on the Generate button. When we click on the Generate button, it starts packing the project in a .zip(spring-boot-gcp-logging-example) file and downloads the project. Then, Extract the Zip file. 

Then, import the project on your favourite IDE.

Final Project directory:

In the pom.xml, add Stackdriver Logging Starter:

<!-- Starter for Stackriver Logging -->
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>spring-cloud-gcp-starter-logging</artifactId>
</dependency>


In order to make the deployment to App Engine easier, we include Google Cloud App Engine Apache Maven Plugin to our pom.xml.
<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>appengine-maven-plugin</artifactId>
<version>2.2.0</version>
<configuration>
<version>1</version>
<projectId>GCLOUD_CONFIG</projectId>
</configuration>
</plugin>


Complete pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.9</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.knf.dev.demo</groupId>
<artifactId>spring-boot-gcp-logging-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-gcp-logging-example</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>11</java.version>
<spring-cloud-gcp.version>3.4.6</spring-cloud-gcp.version>
<spring-cloud.version>2021.0.6</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>spring-cloud-gcp-starter</artifactId>
</dependency>
<!-- Starter for Stackriver Logging -->
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>spring-cloud-gcp-starter-logging</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>spring-cloud-gcp-dependencies</artifactId>
<version>${spring-cloud-gcp.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>com.google.cloud.tools</groupId>
<artifactId>appengine-maven-plugin</artifactId>
<version>2.2.0</version>
<configuration>
<version>1</version>
<projectId>GCLOUD_CONFIG</projectId>
</configuration>
</plugin>
</plugins>
</build>

</project>


app.yaml

To deploy the application to App Engine standard environment, you must create an appengine folder in the main directory: src/main/appengine/ and create an app.yaml file inside the appengine folder and add the following content.
runtime: java11
instance_class: F1


Create Test Controller

package com.knf.dev.demo.controller;

import org.springframework.web.bind.annotation.RestController;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.GetMapping;

/** Sample REST Controller to demonstrate Stackdriver Logging. */
@RestController
public class TestController {

private static final Log LOGGER = LogFactory.
getLog(TestController.class);

@GetMapping("/test")
public String test() {

LOGGER.info("This is Info");
LOGGER.warn("This is Warning");
LOGGER.error("This is Error");

return "Testing.....";
}
}
  • Spring @RestController annotation is used to create RESTful web services using Spring MVC. Spring RestController takes care of mapping request data to the defined request handler method. Once response body is generated from the handler method, it converts it to JSON response.
  • @GetMapping annotation for mapping HTTP GET requests onto specific handler methods.

Application.java

package com.knf.dev.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

}

Application is the entry point that sets up the Spring Boot application. The @SpringBootApplication annotation enables auto-configuration and component scanning.


2. Upload Source code on GitHub

First, sign in to Github https://github.com/ 

Then, upload the source code from your local machine to the GitHub.


3. Create a GCP Project

First, Sign into the Google console at https://console.cloud.google.com.

You can create a new project by first selecting the project dropdown in the top left and selecting "New Project".


Next, specify your GCP Project name and Project ID.

Then Click on the "CREATE" button.

Copy "Project ID" and keep it for future purposes.


4. Enable Cloud Logging API

From cloud console, search for "Cloud Logging API" like below and click on "Cloud Logging API" button.


Next, click on "ENABLE" button,


5. Deploy the application to App Engine

Start the Google Cloud Shell in the browser.
Button to activate cloud shell is marked in the below image.


Next, clone the git repository:

git clone https://github.com/knowledgefactory4u/spring-cloud-gcp-examples.git


When creating an application in App Engine, we need to choose a region where the application will be running. The list of regions can be shown by executing the command:

gcloud app regions list

We will choose region us-west4 and create our AppEngine app:

gcloud app create --region us-west4


Change the directory to spring-boot-gcp-logging-example.

cd spring-cloud-gcp-examples/spring-boot-gcp-logging-example

From within your git repository directory, you can deploy your application by executing below command.

mvn -DskipTests package appengine:deploy

If everything goes fine, then you will see the following similar output in your cloud shell:

Copy the URL of the deployed service. 


6. Test the API using Postman

Add an X-Cloud-Trace-Context header to the request. The header specification is:

"X-Cloud-Trace-Context: TRACE_ID/SPAN_ID;o=TRACE_TRUE"

  • TRACE_ID is a 32-character hexadecimal value representing a 128-bit number. It should be unique between your requests, unless you intentionally want to bundle the requests together.
  • SPAN_ID is the decimal representation of the (unsigned) span ID. It should be randomly generated and unique in your trace.


7. Go to the “Logs Explorer” in GCP and check the log

In the search bar, enter "Logging" and choose "Logging" in the result list to navigate to the Logs Explorer.

Then, set our resource to GAE Application and set log name as spring.log.

Or

You can use the following to filter by the trace ID:

resource.type="gae_app"
log_name="projects/knf-gcp-demo-project-123/logs/spring.log"
trace="projects/knf-gcp-demo-project-123/traces/705445aa7843bc8bf206b12000100000"


More Spring|GCP Examples - click here!

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Spring Boot + Mockito simple application with 100% code coverage

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete