1. Introduction
1.绪论
Adding some color can make logging much easier to read.
添加一些颜色可以使日志更容易阅读。
In this article, we’ll see how to add color to our logs for consoles such as the Visual Studio Code terminal, Linux, and Windows command prompt.
在这篇文章中,我们将看到如何为Visual Studio Code终端、Linux和Windows命令提示符等控制台的日志添加颜色。
Before we start, let’s note that, unfortunately, there are only limited color settings in the Eclipse IDE console. The console within Eclipse IDE does not support color determined by Java code, so the solutions presented in this article will not work within the Eclipse IDE console.
在我们开始之前,让我们注意一下,不幸的是,在Eclipse IDE控制台中只有有限的颜色设置。Eclipse IDE 中的控制台不支持由 Java 代码决定的颜色,因此,本文介绍的解决方案在 Eclipse IDE 控制台中无法使用。
2. How to Use ANSI Codes to Color Logs
2.如何使用ANSI代码为日志着色
The easiest way to achieve colorful logging is by using ANSI escape sequences, often referred to as ANSI codes.
实现彩色日志的最简单方法是使用ANSI转义序列,通常被称为ANSI代码。
ANSI codes are special sequences of bytes that some terminals interpret as a command.
ANSI代码是特殊的字节序列,一些终端将其解释为一个命令。
Let’s log out an ANSI code:
让我们登录出一个ANSI代码。
System.out.println("Here's some text");
System.out.println("\u001B[31m" + "and now the text is red");
In the output, we see that the ANSI code was not printed, and the color of the font has changed to red:
在输出中,我们看到ANSI代码没有被打印出来,而且字体的颜色也变成了红色。
Here's some text
and now the text is red
Let’s note that we need to make sure we reset the font color once we’re done logging.
让我们注意,我们需要确保在完成记录后重置字体颜色。
Fortunately, this is easy. We can simply print \u001B[31m, which is the ANSI reset command.
幸运的是,这很容易。我们可以简单地打印\u001B[31m,这是ANSI的复位命令。
The reset command will reset the console to its default color. Note that this may not necessarily be black, it could be white, or any other color configured by the console. For example:
reset命令将把控制台重置为其默认颜色。注意,这不一定是黑色,可能是白色,或者是控制台配置的任何其他颜色。比如说。
System.out.println("Here's some text");
System.out.println("\u001B[31m" + "and now the text is red" + "\u001B[0m");
System.out.println("and now back to the default");
Gives the output:
给出了输出。
Here's some text
and now the text is red
and now back to the default
Most logging libraries will obey ANSI codes, which allows us to build some colorful loggers.
大多数日志库都会遵守ANSI代码,这使得我们可以建立一些丰富多彩的记录器。
For example, we could quickly construct a logger that uses different colors for different log levels.
例如,我们可以快速构建一个日志器,对不同的日志级别使用不同的颜色。
public class ColorLogger {
private static final Logger LOGGER = LoggerFactory.getLogger(ColorLogger.class);
public void logDebug(String logging) {
LOGGER.debug("\u001B[34m" + logging + "\u001B[0m");
}
public void logInfo(String logging) {
LOGGER.info("\u001B[32m" + logging + "\u001B[0m");
}
public void logError(String logging) {
LOGGER.error("\u001B[31m" + logging + "\u001B[0m");
}
}
Let’s use this to print some color to the console:
让我们用它来打印一些颜色到控制台。
ColorLogger colorLogger = new ColorLogger();
colorLogger.logDebug("Some debug logging");
colorLogger.logInfo("Some info logging");
colorLogger.logError("Some error logging");
[main] DEBUG com.baeldung.color.ColorLogger - Some debug logging [main] INFO com.baeldung.color.ColorLogger - Some info logging [main] ERROR com.baeldung.color.ColorLogger - Some error logging
We can see that each log level is a different color, making our logs much more readable.
我们可以看到,每个日志级别都是不同的颜色,使我们的日志更容易阅读。
Finally, ANSI codes can be used to control much more than just font color – we can control background colors and font-weight, and style. There’s a selection of these ANSI codes in the example project.
最后,ANSI代码可以用来控制的不仅仅是字体颜色–我们可以控制背景颜色和字体重量,以及样式。在示例项目中就有这些ANSI代码的选择。
3. How to Color Logs in the Windows Command Prompt
3.如何在Windows命令提示符中给日志着色
Unfortunately, some terminals don’t support ANSI codes. One prime example is the Windows command prompt, and the above won’t work. Therefore, we need a more sophisticated solution.
不幸的是,有些终端不支持ANSI代码。一个最好的例子是Windows的命令提示符,上面的方法就行不通了。因此,我们需要一个更复杂的解决方案。
However, rather than trying to implement it ourselves, we can leverage an established library called JANSI to our pom.xml:
但是,我们可以利用一个名为JANSI的既定库来实现我们的pom.xml,而不是试图自己实现它。
<dependency>
<groupId>org.fusesource.jansi</groupId>
<artifactId>jansi</artifactId>
<version>2.4.0</version>
</dependency>
Now to log in color, we can simply call into the ANSI API that JANSI provides:
现在要登录颜色,我们可以简单地调用JANSI提供的ANSI API。
private static void logColorUsingJANSI() {
AnsiConsole.systemInstall();
System.out.println(ansi()
.fgRed()
.a("Some red text")
.fgBlue()
.a(" and some blue text")
.reset());
AnsiConsole.systemUninstall();
}
This produces the text:
这就产生了文本。
Some red text and some blue text
Let’s note that we have to first install the AnsiConsole, and uninstall it once we’re done.
让我们注意到,我们必须首先安装AnsiConsole,一旦完成就卸载它。
As with ANSI codes, JANSI also provides a large range of logging formats.
与ANSI代码一样,JANSI也提供了大量的记录格式。
JANSI achieves this functionality by detecting the terminal being used and invoking the appropriate platform-specific API required. This means that when JANSI detects a Windows Command Prompt, rather than use ANSI codes that don’t work, it invokes libraries that use Java Native Interface (JNI) methods.
JANSI通过检测正在使用的终端并调用所需的适当的特定平台API来实现这一功能。这意味着,当JANSI检测到Windows命令提示符时,它不是使用不起作用的ANSI代码,而是调用使用Java本地接口(JNI)方法的库。
Also, JANSI doesn’t just work on the Windows command prompt – it is able to cover most terminals (although the Eclipse IDE console is not one of them, due to the limited settings in Eclipse for colored text).
另外,JANSI不只是在Windows命令提示符上工作–它能够覆盖大多数终端(尽管Eclipse IDE控制台不是其中之一,因为Eclipse中对彩色文本的设置有限)。
Finally, JANSI will also ensure it strips out unwanted ANSI codes when the environment doesn’t require them, helping to keep our logs clean and tidy.
最后,JANSI还将确保在环境不需要ANSI代码时将其剥离出来,帮助保持我们的日志干净整洁。
Overall, JANSI provides us with a powerful and convenient way to log in color to most environments and terminals.
总的来说,JANSI为我们提供了一个强大而方便的方式,可以在大多数环境和终端上进行彩色登录。
4. Conclusion
4.总结
In this article, we learned how to use ANSI codes to control the color of the console font and saw an example of how we could distinguish log levels using color.
在这篇文章中,我们学习了如何使用ANSI代码来控制控制台字体的颜色,并看到了一个如何使用颜色来区分日志级别的例子。
Finally, we found that not all consoles support ANSI codes and highlighted one such library, JANSI, that provides more sophisticated support.
最后,我们发现并不是所有的控制台都支持ANSI代码,并强调了一个这样的库,JANSI,它提供了更复杂的支持。
As always, the example project is available over on GitHub.
一如既往,该示例项目可在GitHub上获得。