5

我想在 spring-shell 中为我的控制台输出着色。就像是:

System.out.println("\red; red text");

我知道彩色的 JUL 日志输出,但这还不够。

我怎么能这样做?

4

2 回答 2

10

您可以在输出中使用 Ansi 值。

这是我的课程,其中包含一些颜色常量:

public class AnsiConstants {
  public static final String ANSI_RESET = "\u001B[0m";
  public static final String ANSI_BLACK = "\u001B[30m";
  public static final String ANSI_RED = "\u001B[31m";
  public static final String ANSI_GREEN = "\u001B[32m";
  public static final String ANSI_YELLOW = "\u001B[33m";
  public static final String ANSI_BLUE = "\u001B[34m";
  public static final String ANSI_PURPLE = "\u001B[35m";
  public static final String ANSI_CYAN = "\u001B[36m";
  public static final String ANSI_GRAY = "\u001B[37m";
  public static final String ANSI_WHITE = "\u001B[37;1m"; 
}

您的示例可以通过以下方式生成:

System.out.println(ANSI_RED + "red text" + ANSI_RESET);
于 2013-11-04T14:41:35.827 回答
4

如果您基于 Spring Boot,使用AnsiOutputAnsiColor应该可以工作。例子:

@SpringBootApplication
public class Application {

  @EventListener
  public void onApplicationReady(ApplicationReadyEvent event) {
    System.out.println(AnsiOutput.toString(
        AnsiColor.GREEN, "Service started successfully", AnsiColor.DEFAULT));
  }

  @EventListener
  public void onApplicationFailed(ApplicationFailedEvent event) {
    System.err.println(AnsiOutput.toString(
        AnsiColor.RED, "Service startup failed", AnsiColor.DEFAULT));
  }

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

}
于 2016-09-15T14:34:16.103 回答