Lecture 35: Spring Boot Actuator, Runners & Logging

BMC201 - Web Technology

Dr. Prashant Kumar Nag

2026-04-22

Lecture 35

Spring Boot Actuator, Runners & Logging

Week 9 | Unit V: Spring Boot & REST Services
BMC201 - Web Technology
Dr. Prashant Kumar Nag, Assistant Professor

Learning Objectives


  • Understand Spring Boot Actuator and its production-ready features
  • Configure and use Actuator endpoints for monitoring
  • Implement ApplicationRunner and CommandLineRunner
  • Configure logging in Spring Boot applications
  • Use different logging frameworks (Logback, Log4j2)
  • Implement custom logging configuration

Prerequisites


Before this lecture, quickly revise:

  • Spring Boot Configuration & Setup from Lecture 33
  • Spring Boot Annotations from Lecture 34
  • Basic understanding of application monitoring concepts

Syllabus Mapping


  • Unit V topic focus: Spring Boot Actuator, Runners & Logging
  • CO alignment: implementation understanding + production monitoring
  • Assessment alignment: short definitions + long implementation/design questions

Agenda


  • 5-minute recap from previous lecture
  • Concept deep dive: Spring Boot Actuator, Runners & Logging
  • Code/configuration walkthrough and output analysis
  • Debug checklist and exam-oriented summary

Introduction


Spring Boot Actuator provides production-ready features for monitoring and managing applications, while runners enable initialization logic and logging provides observability.

Think About It


How do you monitor a production application’s health, metrics, and logs without manually adding monitoring code everywhere?

Spring Boot Actuator Overview


Spring Boot Actuator is a sub-project that provides production-ready features:

  • Health checks
  • Application metrics
  • Environment information
  • HTTP trace logging
  • Audit events
  • Custom endpoints

Actuator exposes endpoints over HTTP or JMX for monitoring and management.

Adding Actuator Dependency


Maven:

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

Gradle:

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

After adding, start your app and visit:

http://localhost:8080/actuator

Common Actuator Endpoints


Endpoint Purpose Enabled by Default
/actuator/health Application health status Yes (HTTP & JMX)
/actuator/info Application information Yes (HTTP & JMX)
/actuator/metrics Application metrics No (HTTP), Yes (JMX)
/actuator/env Environment properties No (HTTP), Yes (JMX)
/actuator/loggers Logging configuration No (HTTP), Yes (JMX)
/actuator/beans All Spring beans No (HTTP), Yes (JMX)
/actuator/httptrace HTTP request/response trace No

Most endpoints are disabled by default for security reasons.

Enabling Actuator Endpoints


# Expose all endpoints over HTTP
1management.endpoints.web.exposure.include=*      //

# Expose specific endpoints
2management.endpoints.web.exposure.include=health,info,metrics //

# Exclude specific endpoints
3management.endpoints.web.exposure.exclude=env,beans //
1
NOT recommended for production — exposes sensitive data
2
Whitelist specific endpoints for production use
3
Blacklist endpoints you don’t want exposed

Custom base path:

management.endpoints.web.base-path=/manage
# Now: http://localhost:8080/manage/health

Health Endpoint in Detail


GET /actuator/health

{
  "status": "UP",                                // #<1>
  "components": {
    "diskSpace": { "status": "UP" },
    "db": { "status": "UP" },
    "ping": { "status": "UP" }
  }
}
  1. Status can be: UP, DOWN, OUT_OF_SERVICE, UNKNOWN

Show detailed health information:

2management.endpoint.health.show-details=always   //
2
Shows component-level details; options: never, when-authorized, always

Custom Health Indicator


@Component
public class CustomHealthIndicator implements HealthIndicator {

  @Override
  public Health health() {                       // #<1>
    boolean isHealthy = checkExternalService();
    
    if (isHealthy) {
      return Health.up()                         // #<2>
        .withDetail("service", "External API")
        .withDetail("status", "reachable")
        .build();
    } else {
      return Health.down()                       // #<3>
        .withDetail("service", "External API")
        .withDetail("error", "Connection timeout")
        .build();
    }
  }
}
  1. Implement health() method to return health status
  2. Report healthy status with custom details
  3. Report unhealthy status with error details

Info Endpoint Configuration


# Static information in application.properties
1info.app.name=My Spring Boot Application       //
info.app.version=1.0.0
info.app.description=Demo application for course

# Display build information (from Maven/Gradle)
2management.info.build.enabled=true              //
management.info.env.enabled=true
1
Custom key-value pairs added to /actuator/info
2
Automatically include build information from build file

Response:

{
  "app": {
    "name": "My Spring Boot Application",
    "version": "1.0.0",
    "description": "Demo application for course"
  }
}

Metrics Endpoint


GET /actuator/metrics

Returns available metrics:

{
  "names": [
    "jvm.memory.used",
    "jvm.threads.live",
    "http.server.requests",
    "system.cpu.usage",
    "process.uptime"
  ]
}

Get specific metric:

GET /actuator/metrics/jvm.memory.used
{
  "name": "jvm.memory.used",
  "value": 123456789,
  "unit": "bytes"
}

ApplicationRunner Interface


ApplicationRunner runs code after Spring Boot app starts up.

@Component
public class DataLoader implements ApplicationRunner {

  @Override
  public void run(ApplicationArguments args) throws Exception { // #<1>
    System.out.println("Application started!");
    // Load initial data, warm up caches, etc.
  }
}
  1. run() method executes after application context is ready

Use cases: - Preload database data - Initialize cache - Check external service connectivity

CommandLineRunner Interface


CommandLineRunner is similar to ApplicationRunner but receives raw command-line arguments.

@Component
public class StartupRunner implements CommandLineRunner {

  @Override
  public void run(String... args) throws Exception {        // #<1>
    System.out.println("Command line args:");
    for (String arg : args) {
      System.out.println(arg);
    }
  }
}
  1. Receives command-line arguments as a string array

ApplicationRunner vs CommandLineRunner


Aspect ApplicationRunner CommandLineRunner
Parameter type ApplicationArguments String... args
Parsing Structured (options, values) Raw string array
When to use Need structured argument access Simple string processing
Execution order Same (controlled by @Order) Same (controlled by @Order)

Control execution order:

@Component
@Order(1)                                         // #<1>
public class FirstRunner implements ApplicationRunner { ... }

@Component
@Order(2)                                         // #<2>
public class SecondRunner implements ApplicationRunner { ... }
  1. Runs first (lower number = higher priority)
  2. Runs second

Logging in Spring Boot


Spring Boot uses Logback by default (SLF4J API).

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class UserService {
  private static final Logger log = LoggerFactory.getLogger(UserService.class); // #<1>

  public void createUser(String name) {
    log.debug("Creating user: {}", name);        // #<2>
    log.info("User created successfully: {}", name); // #<3>
    log.warn("User limit approaching");
    log.error("User creation failed", exception);
  }
}
  1. Create logger instance for the class
  2. Log levels: TRACE < DEBUG < INFO < WARN < ERROR
  3. Use parameterized logging (not string concatenation)

Logging Levels Configuration


# Set root logging level
1logging.level.root=INFO                          //

# Set package-level logging
2logging.level.com.example.myapp=DEBUG            //
logging.level.com.example.myapp.service=TRACE

# Set framework logging
3logging.level.org.springframework.web=DEBUG      //
logging.level.org.hibernate.SQL=DEBUG
1
Default level for all loggers
2
Package-specific levels override root level
3
Enable framework debug logging for troubleshooting

Logging to File


# Log to a specific file
1logging.file.name=app.log                        //

# Or log to a directory (file name is spring.log)
2logging.file.path=/var/logs                      //

# Configure file rotation
3logging.logback.rollingpolicy.max-file-size=10MB //
logging.logback.rollingpolicy.max-history=30
1
Log file in current directory
2
Log file at specified path
3
Rotate when file reaches 10MB, keep 30 days of history

Custom Logback Configuration


Create logback-spring.xml in src/main/resources:

<configuration>
  <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>

  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>logs/application.log</file>
    <encoder>
      <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n</pattern>
    </encoder>
  </appender>

  <root level="INFO">
    <appender-ref ref="CONSOLE" />
    <appender-ref ref="FILE" />
  </root>
</configuration>

Alternative Logging Frameworks


Switch to Log4j2:

<!-- Exclude Logback, include Log4j2 -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
  <exclusions>
    <exclusion>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-logging</artifactId>
    </exclusion>
  </exclusions>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

Then create log4j2-spring.xml for configuration.

Common Mistakes to Avoid


  • Exposing all Actuator endpoints (*) in production
  • Not securing Actuator endpoints with Spring Security
  • Forgetting to implement ApplicationRunner/CommandLineRunner with @Component
  • Using System.out.println() instead of proper logging
  • Setting logging level to DEBUG/TRACE in production
  • Not configuring log file rotation — disk fills up

AKTU Exam-Oriented Checklist


Prepare these high-probability questions:

  1. What is Spring Boot Actuator and list common endpoints?
  2. Explain health endpoint and custom health indicators
  3. Differentiate ApplicationRunner and CommandLineRunner
  4. Explain logging levels and configuration in Spring Boot
  5. How to configure logging to file with rotation?
  6. Compare Logback and Log4j2

Summary


You now understand:

  • Spring Boot Actuator for production monitoring
  • Common Actuator endpoints and custom health indicators
  • ApplicationRunner and CommandLineRunner for startup logic
  • Logging configuration and levels in Spring Boot
  • File-based logging with rotation
  • Alternative logging frameworks (Logback vs Log4j2)

Memory Booster


Syllabus memory points for Spring Boot Actuator, Runners & Logging:

  • Core recall: Actuator endpoints (health, info, metrics), ApplicationRunner vs CommandLineRunner, logging levels
  • Exam compare: ApplicationRunner vs CommandLineRunner, Logback vs Log4j2
  • Practical anchor: Enable Actuator endpoints and configure custom health indicator

Live Demo


Live implementation for Spring Boot Actuator, Runners & Logging:

📋 Open Demo: Lecture 35 - Spring Boot Actuator, Runners & Logging

Demo checklist: - enable and access Actuator endpoints - implement a custom health indicator - create ApplicationRunner to load initial data - configure logging levels and file output

Resources & References


Structured Debug Checklist


  1. verify spring-boot-starter-actuator dependency is added
  2. check Actuator endpoint exposure in application.properties
  3. ensure runners implement correct interface and have @Component
  4. validate logging configuration syntax in logback-spring.xml
  5. check log file permissions if file logging fails

Exam Preparation Questions: Short


  • Define Spring Boot Actuator and list three common endpoints.
  • What is the purpose of /actuator/health endpoint?
  • Differentiate ApplicationRunner and CommandLineRunner.
  • Explain logging levels in order of severity.
  • How to configure logging to file in Spring Boot?

Exam Preparation Questions: Long


  • Explain Spring Boot Actuator with endpoint examples and security considerations.
  • Discuss ApplicationRunner and CommandLineRunner with use cases and execution order.
  • Explain logging configuration in Spring Boot including Logback customization.
  • Describe custom health indicators and metrics collection.

Practice Task


  • Implement: Create a Spring Boot application with Actuator monitoring.
  • Add custom health indicator to check database connectivity.
  • Implement ApplicationRunner to initialize cache data.
  • Configure logging with file rotation and custom levels.
  • Document one Actuator configuration mistake you encountered and the fix.

Checklist


Can you:

  • explain Spring Boot Actuator, Runners & Logging in your own words?
  • configure and secure Actuator endpoints?
  • implement startup logic using runners?
  • configure logging for different environments?

Next Lecture


  • Topic: Lecture 36 - REST Controllers & Request Mapping
  • Preparation required: revise this lecture summary and practice configuring Actuator

Spring Boot Actuator, Runners & Logging

Next: Lecture 36 - REST Controllers & Request Mapping