Open In App

Monitoring and Logging in Spring Boot

Last Updated : 05 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Spring Boot is one of the most popular application development frameworks among developers. Spring boot can be used to develop standalone Java enterprise-level applications. Spring framework also provides features for ease of development and better security and performance in spring applications. Though Logging and Monitoring are not always required to build and maintain Spring applications, it’s a good practice to include features of logging and monitoring in our application. It becomes essential for entry-ready applications to have logging features and monitoring features.

  • Monitoring helps to gain insight information about the application which can help improve performance, avoid bottleneck conditions, and optimize resources used for stable application and better performance.
  • Logging helps determine reasons in case an unexpected situation appears for the application. Logs help to determine core reasons and resolve issues.

Through this article, we will learn how we can implement Logging and Monitoring in Spring Boot Applications. If you are new to Spring Application development, check out the tutorial of Spring Boot on GFG – Spring Boot Tutorial

Monitoring in Spring Boot

Spring Boot comes with additional features for Management and Monitoring Spring applications. Monitoring becomes very helpful when we push our application in production. We can check all the details about our application and manage it using HTTP endpoints. For Monitoring purposes, we are going to use Spring Boot Actuator.

Step 1: Create a Spring Boot project

Go to start.spring.io and create a spring boot project. Choose the configuration as follows:

  • Project: Maven
  • Language: Java
  • Spring Boot: 3.2.1
  • Packaging: Jar
  • Java: 17
  • Dependencies: Spring Web

Download the spring project and open in any IDE.

Project Metadata

Step 2: Add Spring Boot Actuator Dependency

Once you open your project in an IDE, navigate to pom.xml file.

Project Folder Structure

Now add the following dependency for Spring boot actuator:

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>

If you are using a Gradle build, use the following:

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-actuator'
}

Now wait for some-time for Spring boot to configure the dependency automatically.

Pom.xml

XML




<?xml version="1.0" encoding="UTF-8"?>
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.2.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.Monitoring</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>Gfg</name>
    <description>Demo project for Spring Boot Monitoring</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
  
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
      
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
  
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
  
</project>


Step 3: Application Configuration

Open application.properties file inside resource folder and add the following configurations:

management. endpoints.web.base-path=/admin
management.endpoints.web.exposure. include=*
management. endpoint.health.show-details=always

The above code will allow us to see Monitoring information on “/admin” page and we will be able to see endpoints for monitoring. We have also enabled health status to show all details always.

Step 4: Monitor Spring Boot application

Run your spring boot application which will by default start at port no 8080. Please keep in mind that we haven’t created any controller so you will see a “Whitelabel Error Page” at localhost:8080.

Application started on tomcat port number 8080

After we have run our application, you can see that it is exposing 13 endpoints for Monitoring purpose, and we can access it on “localhost:8080/admin“. Let’s open our web browser and see if we can monitor.

localhost:8080/admin

localhost:8080/admin

{
"_links": {
"self": {
"href": "http://localhost:8080/admin",
"templated": false
},
"beans": {
"href": "http://localhost:8080/admin/beans",
"templated": false
},
"caches-cache": {
"href": "http://localhost:8080/admin/caches/{cache}",
"templated": true
},
"caches": {
"href": "http://localhost:8080/admin/caches",
"templated": false
},
"health": {
"href": "http://localhost:8080/admin/health",
"templated": false
},
"health-path": {
"href": "http://localhost:8080/admin/health/{*path}",
"templated": true
},
"info": {
"href": "http://localhost:8080/admin/info",
"templated": false
},
"conditions": {
"href": "http://localhost:8080/admin/conditions",
"templated": false
},
"configprops": {
"href": "http://localhost:8080/admin/configprops",
"templated": false
},
"configprops-prefix": {
"href": "http://localhost:8080/admin/configprops/{prefix}",
"templated": true
},
"env": {
"href": "http://localhost:8080/admin/env",
"templated": false
},
"env-toMatch": {
"href": "http://localhost:8080/admin/env/{toMatch}",
"templated": true
},
"loggers": {
"href": "http://localhost:8080/admin/loggers",
"templated": false
},
"loggers-name": {
"href": "http://localhost:8080/admin/loggers/{name}",
"templated": true
},
"heapdump": {
"href": "http://localhost:8080/admin/heapdump",
"templated": false
},
"threaddump": {
"href": "http://localhost:8080/admin/threaddump",
"templated": false
},
"metrics-requiredMetricName": {
"href": "http://localhost:8080/admin/metrics/{requiredMetricName}",
"templated": true
},
"metrics": {
"href": "http://localhost:8080/admin/metrics",
"templated": false
},
"scheduledtasks": {
"href": "http://localhost:8080/admin/scheduledtasks",
"templated": false
},
"mappings": {
"href": "http://localhost:8080/admin/mappings",
"templated": false
}
}
}

The above is the output we are getting at “/admin” which include bean information, mapping information, metrics, cache, scheduled tasks and other details about the spring boot application. You can individually click on the links provided for more specific monitoring.

Let’s check the health section:

http://localhost:8080/admin/health

localhost:8080/admin/health

So, we are able to see that our application is running without any issues and details like diskspace, ping, etc. are provided for monitoring.

Logging in Spring Boot

Spring Boot uses SLF4J (Simple Logging Facade for Java) for logging, and Logback as the default logging implementation. We can customize logging configurations by providing xml file in our classpath. This allows us to control log levels, appenders, and formatting. Different log levels are DEBUG, INFO, WARN, ERROR. We can configure log levels appropriately to ensure that our logs provide the necessary information without providing us logs with unnecessary details. To manage log file sizes and prevent them from growing indefinitely, we can configure Logback rolling policies.

To implement Logging the first step will be creating a Spring boot application, as we have already created on for Monitoring, we will use the same. You can create a new one if you want. Follow step 1 of Monitoring in Spring Boot for reference. Now when we create Spring boot application, spring boot starters do all necessary configurations for us and here we can trigger the logging features with just creating a Controller and we will be able to see logs in the console.

Let’s Create one Controller and name it LoggingController.

LoggingController.java

Java




import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LoggingController {
    Logger logger = LoggerFactory.getLogger(LoggingController.class);
    @RequestMapping("/")
    public String index() {
        logger.info("INFO Message");
        logger.warn("WARN Message");
        logger.error("ERROR Message");
        return "Hello World!.";
    }
}


Here our controller is mapped to “/” in localhost and will print “Hello World!” message.

Output Screen

We have used Logger logger = LoggerFactory.getLogger(LoggingController.class); which is logging in a Java application, especially when using the SLF4J logging framework with Logback as the underlying implementation.

  • Logger: Logger in Java are objects which trigger log events. Logger is an interface provided by SLF4J. It serves as an abstraction over different logging implementations (such as Logback, Log4j, or Java Util Logging).
  • LoggerFactory: The LoggerFactory is a class provided by SLF4J that produces Logger instances. It acts as a factory for creating loggers with the appropriate configuration and settings.
  • getLogger(LoggingController.class): This method of LoggerFactory is used to obtain a Logger instance. It takes a Class<?> parameter, typically the class in which the logger is declared. In this case, it’s the LoggingController.class.

Let’s run the application and check the console for Logs.

Console Output

Now we can configure the Logging as per our needs. To store the logs, we can create one log file and store them. These all-logging configurations are requirement specific and can be implemented for your ease of tracing.

Conclusion

Spring boot comes with spring starter and actuator being one of the components of spring boot makes the configurations easy for Monitoring and Logging. Tools like Spring Boot Actuator, Spring Boot Admin, and Logback provides developers with capabilities to ensure that their application is reliable and optimized for performance. By using best practices in monitoring and logging, we can easily identify and address issues, leading to a more robust and stable application.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads