Significantly improve logging

Allow System.out.print messages to appear
Binding cleanup
This commit is contained in:
nathanrsxtn
2022-03-21 12:29:03 -06:00
parent 810c1e3289
commit 6d8ddaa068
5 changed files with 95 additions and 313 deletions
+56 -69
View File
@@ -2,8 +2,8 @@ package frc4388.utility;
import static org.fusesource.jansi.Ansi.ansi;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
@@ -11,78 +11,64 @@ import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Map;
import java.util.Optional;
import java.util.logging.ConsoleHandler;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.StreamHandler;
import org.fusesource.jansi.Ansi;
import org.fusesource.jansi.Ansi.Attribute;
import org.fusesource.jansi.Ansi.Color;
import org.fusesource.jansi.AnsiConsole;
import org.fusesource.jansi.AnsiPrintStream;
public class AnsiLogging {
private static final AnsiPrintStream ANSI_CONSOLE_STREAM = AnsiConsole.out();
private static final Level LEVEL = Level.ALL;
public class AnsiLogging extends ConsoleHandler {
public static void systemInstall() {
try {
// Configure java.util.logging.Logger to output additional colored information.
LogManager.getLogManager().updateConfiguration(key -> (o, n) -> {
switch (key) {
case ".level":
return Level.ALL.getName();
return LEVEL.getName();
case "handlers":
return AnsiColorConsoleHandler.class.getName();
return LoggingAnsiConsoleHandler.class.getName();
default:
return n;
}
});
// Replace standard output streams with org.fusesource.jansi.AnsiPrintStreams.
AnsiConsole.systemInstall();
// Replace standard output stream with java.util.logging.Logger.
System.setOut(printStreamLogger(Logger.getGlobal(), Level.INFO));
// Replace standard error output stream with java.util.logging.Logger.
System.setErr(printStreamLogger(Logger.getGlobal(), Level.SEVERE));
// Set the console to process ANSI escape codes.
ANSI_CONSOLE_STREAM.install();
// Sends standard output stream messages through a logger.
System.setOut(printStreamLogger(Logger.getGlobal(), "out", Level.INFO));
// Sends standard error output stream messages through a logger.
System.setErr(printStreamLogger(Logger.getGlobal(), "err", Level.SEVERE));
} catch (IOException exception) {
exception.printStackTrace(AnsiConsole.sysErr());
}
}
/**
* This class is a ConsoleHandler that uses ANSI escape codes to colorize the output
* This class is a StreamHandler that uses ANSI escape codes to colorize the log messages
*/
public static class AnsiColorConsoleHandler extends ConsoleHandler {
@Override
public void publish(LogRecord logRecord) {
AnsiConsole.err().print(getFormatter().format(logRecord));
AnsiConsole.err().flush();
public static class LoggingAnsiConsoleHandler extends StreamHandler {
public LoggingAnsiConsoleHandler() {
super(ANSI_CONSOLE_STREAM, new LoggingAnsiFormatter());
setLevel(LEVEL);
}
@Override
public Formatter getFormatter() {
return formatter;
}
private static class LoggingAnsiFormatter extends Formatter {
private static final ZoneId ZONE_ID = ZoneId.systemDefault();
// Specify colors for the different message levels.
private static final Map<Integer, String> LEVEL_COLORS = Map.of(Level.OFF.intValue(), "", Level.SEVERE.intValue(), ansi().fgBright(Color.RED).toString(), Level.WARNING.intValue(), ansi().fgBright(Color.YELLOW).toString(), Level.INFO.intValue(), ansi().fg(Color.GREEN).toString(), Level.CONFIG.intValue(), ansi().fgBright(Color.BLUE).toString(), Level.FINE.intValue(), ansi().fg(Color.CYAN).toString(), Level.FINER.intValue(), ansi().fg(Color.MAGENTA).toString(), Level.FINEST.intValue(), ansi().fgBright(Color.BLACK).toString(), Level.ALL.intValue(), ansi().fg(Color.DEFAULT).toString());
private static final String FORMAT = ansi().a("%s").bold().a(Attribute.UNDERLINE).a("[%tb %<td %<tk:%<tM:%<tS.%<tL] %s %s:").boldOff().a(Attribute.UNDERLINE_OFF).a("%s%s").a(Attribute.INTENSITY_FAINT).a("%s").boldOff().reset().newline().toString();
private static final String RESET = ansi().reset().toString();
private static final Formatter formatter = new Formatter() {
private final ZoneId zoneId = ZoneId.systemDefault();
// Specify and prepare formats for messages
private final Map<Integer, String> levelColors = Map.of(
Level.OFF.intValue(), "",
Level.SEVERE.intValue(), makeMessageFormatString(ansi().fgBright(Color.RED)),
Level.WARNING.intValue(), makeMessageFormatString(ansi().fgBright(Color.YELLOW)),
Level.INFO.intValue(), makeMessageFormatString(ansi().fg(Color.GREEN)),
Level.CONFIG.intValue(), makeMessageFormatString(ansi().fgBright(Color.BLUE)),
Level.FINE.intValue(), makeMessageFormatString(ansi().fg(Color.CYAN)),
Level.FINER.intValue(), makeMessageFormatString(ansi().fg(Color.MAGENTA)),
Level.FINEST.intValue(), makeMessageFormatString(ansi().fgBright(Color.BLACK)),
Level.ALL.intValue(), makeMessageFormatString(ansi().fg(Color.DEFAULT))
);
private String makeMessageFormatString(Ansi base) {
return base.bold().a(Attribute.UNDERLINE).a("[%1$tb %1$td %1$tk:%1$tM:%1$tS.%1$tL] %2$s %3$s:").boldOff().a(Attribute.UNDERLINE_OFF).a("%4$s%5$s").a(Attribute.INTENSITY_FAINT).a("%6$s").reset().a("%n").toString();
}
private String makeStackTraceString(Throwable throwable) {
private static String makeStackTraceString(Throwable throwable) {
StringWriter stringWriter = new StringWriter();
try (PrintWriter printWriter = new PrintWriter(stringWriter)) {
printWriter.println();
@@ -93,43 +79,44 @@ public class AnsiLogging extends ConsoleHandler {
@Override
public String format(LogRecord logRecord) {
ZonedDateTime time = ZonedDateTime.ofInstant(logRecord.getInstant(), zoneId);
ZonedDateTime time = ZonedDateTime.ofInstant(logRecord.getInstant(), ZONE_ID);
// Get the logger name, source class name, and/or source method name.
String source = Optional.ofNullable(logRecord.getLoggerName()).or(() -> Optional.ofNullable(logRecord.getSourceClassName())).map(s -> s + " ").orElse("") + Optional.ofNullable(logRecord.getSourceMethodName()).orElse("");
String message = formatMessage(logRecord);
// Get the stack trace of the exception if it was thrown.
String throwable = Optional.ofNullable(logRecord.getThrown()).map(this::makeStackTraceString).orElse("");
String throwable = Optional.ofNullable(logRecord.getThrown()).map(LoggingAnsiFormatter::makeStackTraceString).orElse("");
// Select the appropriate format string for the log level.
String format = levelColors.getOrDefault(logRecord.getLevel().intValue(), levelColors.get(Level.ALL.intValue()));
String color = LEVEL_COLORS.getOrDefault(logRecord.getLevel().intValue(), LEVEL_COLORS.get(Level.ALL.intValue()));
boolean multiline = message.lines().skip(1).findAny().isPresent();
boolean ansi = message.contains("\033");
String prefix = (ansi ? RESET : "") + (multiline ? System.lineSeparator() : " ");
// Format the log message.
return String.format(format, time, source, logRecord.getLevel().getLocalizedName(), message.lines().count() > 1 ? System.lineSeparator() : " ", message.contains("\033") ? "\033[0m" + message : message, throwable);
return String.format(FORMAT, color, time, source, logRecord.getLevel().getLocalizedName(), prefix, message, throwable);
}
};
@Override
public String getHead(Handler h) {
return String.format("%s%s level set to %s%s%n", LEVEL_COLORS.get(h.getLevel().intValue()), h.getClass().getSimpleName(), h.getLevel().getName(), RESET);
}
}
@Override
public synchronized void publish(LogRecord logRecord) {
super.publish(logRecord);
flush();
}
}
/**
* Create a PrintStream that writes to the given logger at the given level
*
* @param logger The logger to use.
* @param level The level of the log message.
* @return A new PrintStream object.
*/
private static PrintStream printStreamLogger(Logger logger, Level level) {
return new PrintStream(new OutputStream() {
// This is a buffer that is used to store the characters that are written to the PrintStream.
private final StringBuilder stringBuilder = new StringBuilder();
/**
* If the character is a newline, flush the buffer to the logger, otherwise add the character to the
* buffer.
*/
private static PrintStream printStreamLogger(Logger logger, String source, Level level) {
return new PrintStream(new ByteArrayOutputStream() {
@Override
public void write(int i) throws IOException {
if (i == '\n') {
logger.log(level, stringBuilder::toString);
stringBuilder.setLength(0);
} else stringBuilder.appendCodePoint(i);
public void flush() throws IOException {
String s = toString();
if (!s.isBlank()) logger.logp(level, null, source, toString());
reset();
}
});
}, true);
}
}