|
package demo; |
|
|
|
import com.fasterxml.jackson.core.type.TypeReference; |
|
import com.fasterxml.jackson.databind.ObjectMapper; |
|
import org.springframework.boot.SpringApplication; |
|
import org.springframework.boot.autoconfigure.SpringBootApplication; |
|
|
|
import java.io.ByteArrayOutputStream; |
|
import java.io.PrintStream; |
|
import java.util.Map; |
|
import java.util.stream.Collectors; |
|
import java.util.stream.Stream; |
|
|
|
@SpringBootApplication |
|
class JsonBannerDemo { |
|
public static void main(String[] args) throws Exception { |
|
// prepares output capturing |
|
PrintStream oldOut = System.out; |
|
ByteArrayOutputStream capture = Stream.of(new ByteArrayOutputStream()) |
|
.peek(out -> System.setOut(new PrintStream(out))).findAny().get(); |
|
|
|
// runs Spring application with activated JSON logging and banner printed to log |
|
// so INGREDIENT #1: spring.main.banner-mode=log |
|
// INGREDIENT #2: a logger capable of logging multi-line strings (e.g. JSON logger) |
|
SpringApplication.run(JsonBannerDemo.class, new String[]{ |
|
"--spring.main.banner-mode=log" |
|
}); |
|
|
|
// restores System.out, prints JSON log containing the escaped banner |
|
// and prints extracted unescaped banner |
|
System.setOut(oldOut); |
|
String bannerJsonLog = capture.toString().split(System.lineSeparator())[0]; |
|
Map<String, Object> json = new ObjectMapper().readValue(bannerJsonLog, new TypeReference<Map<String, Object>>() {}); |
|
String printedBanner = (String) json.get("message"); |
|
System.out.println(Stream.of("JSON formatted log entry:", bannerJsonLog, "", "contains banner completely unchanged if you simply use spring.main.banner-mode=log", printedBanner).collect(Collectors.joining(System.lineSeparator()))); |
|
System.exit(0); |
|
} |
|
} |
Spring Boot banner output does not need to be disabled for JSON formatted logging to work, as this gist shows.
The program has the following output:
If set up correctly the logger should serialize the banner to:
Even the ANSI formatting is correctly escaped.