Backend Development 9 min read

How to Set Up and Secure Spring Boot Admin Server & Client with Dynamic Logging

This guide walks through setting up a Spring Boot Admin server and client, adding security, configuring logging, displaying client IPs, and dynamically adjusting log levels via the SBA UI, providing complete Maven dependencies, Java configuration classes, and YAML settings for a secure, observable Spring Boot ecosystem.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
How to Set Up and Secure Spring Boot Admin Server & Client with Dynamic Logging

Environment and Version Compatibility

SpringBoot 2.3.9.RELEASE with SpringBootAdmin 2.3.1. Note: SpringBootAdmin 2.4.* requires SpringBoot 2.4.*; otherwise startup errors occur.

What is Spring Boot Admin?

Spring Boot Admin (SBA) is a community project for managing and monitoring Spring Boot applications. Applications register to the Admin Server via HTTP or through Spring Cloud service discovery (e.g., Eureka, Consul).

Configure Spring Boot Admin Server

1. Add Maven dependencies

<code><dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-starter-server</artifactId>
    <version>2.3.1</version>
  </dependency>
</dependencies></code>

2. Enable Admin Server in the main class

<code>@SpringBootApplication
@EnableAdminServer
public class SpringBootAdminApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootAdminApplication.class, args);
    }
}</code>

3. Application configuration (application.yml)

<code>server:
  port: 8080
---
spring:
  application:
    name: admin-server
---
spring:
  boot:
    admin:
      context-path: /sba</code>

Start the service and access http://localhost:8080/sba .

Client Registration

1. Add Maven dependencies

<code><dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-starter-client</artifactId>
    <version>2.3.1</version>
  </dependency>
</dependencies></code>

2. Permit all requests (optional security)

<code>@Configuration
public class SecurityPermitAllConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().permitAll()
            .and().csrf().disable();
    }
}</code>

3. Client configuration (application.yml)

<code>server:
  port: 8081
---
spring:
  application:
    name: admin-client
---
spring:
  boot:
    admin:
      client:
        url:
          - http://localhost:8080/sba
        instance:
          prefer-ip: true</code>

Start the client (ensure the server is running).

Display Client IP

Enable IP display by setting prefer-ip: true in the client configuration.

<code>spring:
  boot:
    admin:
      client:
        url:
          - http://localhost:8080
        instance:
          prefer-ip: true</code>

Log Viewing Configuration

Configure log file path or name (only one can be set) and pattern in application.yml :

<code>logging:
  file:
    path: d:/logs
  pattern:
    file: '%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p) %clr(${PID}){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wEx'</code>

Protect Server with Authentication

1. Add security dependency

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

2. Security configuration

<code>@Configuration(proxyBeanMethods = false)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private final AdminServerProperties adminServer;
    private final SecurityProperties security;

    public SecurityConfig(AdminServerProperties adminServer, SecurityProperties security) {
        this.adminServer = adminServer;
        this.security = security;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
        successHandler.setTargetUrlParameter("redirectTo");
        successHandler.setDefaultTargetUrl(this.adminServer.path("/"));
        http.authorizeRequests(authorize -> authorize
                .antMatchers(this.adminServer.path("/assets/**")).permitAll()
                .antMatchers(this.adminServer.path("/actuator/info")).permitAll()
                .antMatchers(this.adminServer.path("/actuator/health")).permitAll()
                .antMatchers(this.adminServer.path("/login")).permitAll()
                .anyRequest().authenticated())
            .formLogin(form -> form.loginPage(this.adminServer.path("/login")).successHandler(successHandler))
            .logout(logout -> logout.logoutUrl(this.adminServer.path("/logout")))
            .httpBasic(Customizer.withDefaults())
            .csrf(csrf -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                .ignoringRequestMatchers(
                    new AntPathRequestMatcher(this.adminServer.path("/instances"), HttpMethod.POST.toString()),
                    new AntPathRequestMatcher(this.adminServer.path("/instances/*"), HttpMethod.DELETE.toString()),
                    new AntPathRequestMatcher(this.adminServer.path("/actuator/**"))))
            .rememberMe(rememberMe -> rememberMe.key(UUID.randomUUID().toString()).tokenValiditySeconds(1209600));
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .withUser(security.getUser().getName())
            .password("{noop}" + security.getUser().getPassword())
            .roles("USER");
    }
}
</code>

3. Server security user configuration

<code>spring:
  boot:
    admin:
      context-path: /sba
  security:
    user:
      name: admin
      password: admin</code>

Dynamic Log Level Adjustment

1. Demo controller with logging

<code>@RestController
@RequestMapping("/demo")
public class DemoController {
    private static Logger logger = LoggerFactory.getLogger(DemoController.class);

    @GetMapping("/{id}")
    public Object index(@PathVariable("id") String id) {
        logger.debug("DEBUG received param: {}", id);
        logger.info("INFO received param: {}", id);
        return id;
    }
}</code>

2. Set initial log level

<code>logging:
  level:
    '[com.pack.controller]': debug</code>

Use the SBA UI to change the log level at runtime; the change is reflected in the console output.

Client Authentication Information Protection

Add security dependency to the client and configure credentials:

<code><dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency></code>
<code>spring:
  boot:
    admin:
      client:
        username: admin
        password: admin
        url:
          - http://localhost:8080/sba
        instance:
          prefer-ip: true
          metadata:
            user.name: ${spring.security.user.name}
            user.password: ${spring.security.user.password}
  security:
    user:
      name: ak
      password: 123456</code>

After restarting, the client registers successfully with the server.

Conclusion

The tutorial demonstrates a complete setup of Spring Boot Admin server and client, securing the server, configuring log files, displaying client IPs, and dynamically adjusting log levels, providing a robust monitoring solution for Spring Boot applications.

JavamonitoringloggingSpring BootsecuritySpring Boot Admin
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.