Answer the question
In order to leave comments, you need to log in
How can I display in Java a different color of messages in the console from a logger, depending on the type of message?
I display logs in the program to the console via java.util.logging.Logger.
package l2p;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
public class ConsoleLogFormatter extends Formatter
{
private static final String CRLF = "\r\n";
private static final SimpleDateFormat tsformat = new SimpleDateFormat("HH:mm:ss.SSS ");
private Date ts = new Date();
@Override
public String format(LogRecord record)
{
StringBuffer output = new StringBuffer();
ts.setTime(record.getMillis());
output.append(tsformat.format(ts));
output.append(record.getMessage());
output.append(CRLF);
if (record.getThrown() != null)
try
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
record.getThrown().printStackTrace(pw);
pw.close();
output.append(sw.toString());
output.append(CRLF);
}
catch (Exception ex)
{}
return output.toString();
}
}
Answer the question
In order to leave comments, you need to log in
In Linux, ANSI escape codes are processed natively, imho. But in Windows you need to run a special program. Here for example: github.com/downloads/adoxa/ansicon/ansi153.zip
You need to run “ansicon.exe -p” in the console and then ANSI processing will appear.
I don't know if it will work on Linux, but it works on Windows.
If you want a different color, then change "[31mWarning!". For example, on "[35mWarning!". The text will be purple.
30 - black. 31 - red. 32 - green. 33 - yellow. 34 - blue. 35 - magenta. 36 - blue. 37 - white.
I'll leave here a couple of links to stackoverflow, where various 3rd party libraries are advised that allow this to be implemented.
I did it a little clumsily, but for now, for the first time, it’s fine: I just output the lines to the console in the formatter itself (the code of which was given in the question) via System.out.println with the assignment of special codes for coloring.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question