CodeGym /Courses /Module 5. Spring /Lecture 120: Logging system events with Actuator

Lecture 120: Logging system events with Actuator

Module 5. Spring
Level 19 , Lesson 9
Available

Let's talk about logs again.

In the real world logs can include:

  • Catching errors and exceptions.
  • Recording key operations, for example, transaction completions.
  • Tracking user activity.
  • Performance analysis via timestamps and request details.

Combining logging with Actuator gives you not only the current app state data but also historical information for analysis, which makes the system very transparent.


Enabling logging via Actuator

Spring Boot Actuator gives a convenient interface to work with your application's logs. This is done through the /actuator/loggers endpoint. With it you can view current logging settings or even change log levels on the fly!

Add dependencies

First, make sure your project has the necessary dependency. Add Actuator if you haven't already:

pom.xml:


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

build.gradle:

implementation 'org.springframework.boot:spring-boot-starter-actuator'

Logging configuration

Spring Boot Actuator lets you manage logging through the application.properties or application.yml config file. For example, you can expose the /loggers endpoint with this line:

management.endpoints.web.exposure.include=loggers

This setting makes the endpoint available for requests. You can check the list of all registered loggers or change their log level on the fly.


What does the /actuator/loggers endpoint show?

When you open the URL /actuator/loggers you'll get a JSON object containing information about all registered Spring loggers.

Example JSON structure:

{
  "levels": ["OFF", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"],
  "loggers": {
    "ROOT": {
      "configuredLevel": "INFO",
      "effectiveLevel": "INFO"
    },
    "com.example.myapp": {
      "configuredLevel": "DEBUG",
      "effectiveLevel": "DEBUG"
    }
  }
}

Here:

  • levels — the allowed logging levels.
  • loggers — current loggers with their settings. The ROOT logger applies to the whole application unless overridden.

Changing log level

You can change the logging level for any app component dynamically via the API. For example, to set the logging level for the package com.example.myapp to TRACE, send an HTTP request:

PUT request:


PUT /actuator/loggers/com.example.myapp
Content-Type: application/json

{
    "configuredLevel": "TRACE"
}

Make sure the change took effect by checking GET /actuator/loggers/com.example.myapp.


Configuring log levels

Logging in Spring Boot is based on popular logging libraries like Logback, Log4j and Java Util Logging. Let's see how to configure logging for different app components.

Example application.properties:


# Default logging level
logging.level.root=INFO

# Logging level for your package
logging.level.com.example.myapp=DEBUG

# SQL query logging (if using JPA)
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

These logging levels can be modified via /actuator/loggers.


Practice: logging controllers

Let's look at a practical scenario: add a few logs to our tutorial project and monitor them via Actuator.

Example controller with logs

Controller:


package com.example.myapp.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    private static final Logger logger = LoggerFactory.getLogger(HelloController.class);

    @GetMapping("/hello")
    public String sayHello() {
        logger.info("INFO: Handling /hello request");
        logger.debug("DEBUG: Additional debug information");
        logger.error("ERROR: Simulated error log (just an example)");
        return "Hello, Spring Boot with Actuator!";
    }
}

In this example we added INFO, DEBUG, and ERROR logs. Now you can check these events in the application's log file and control their visibility via Actuator.


Configuring logging for security

Security logs are especially useful when using Spring Security. Here's how you can enable logging to analyze successful and failed login attempts:

Example application.properties:

logging.level.org.springframework.security=DEBUG

Now authorization and authentication related requests will be logged. This can help you spot suspicious activity.


Practical task: working with logs

Short exercise:

  1. Enable the /actuator/loggers endpoint in your project.
  2. Add logs with different levels (INFO, WARN, DEBUG) to one of your controllers.
  3. Change the logging level on the fly via a PUT request to /actuator/loggers.
  4. Check how the changes are reflected in the logs.

Protecting logs with Spring Security

Remember that log data can be sensitive. Protect the /actuator/loggers endpoint so only authorized users can access it.

Example secure configuration:


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests((requests) -> requests
                .requestMatchers("/actuator/loggers/**").hasRole("ADMIN")
                .anyRequest().authenticated()
        )
        .httpBasic();
        return http.build();
    }
}

Now only users with the ADMIN role will be able to change log levels or view configurations via /actuator/loggers.


Additionally: log analysis

When you combine Actuator with external systems like ELK (Elasticsearch, Logstash, Kibana), logs become even more powerful. You can map requests that led to an error and visualize that data.


Summary

Now your app not only logs errors but also lets you flexibly manage logging settings via Actuator and APIs. This helps minimize time to find and fix issues and gives you more control over application monitoring.

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION