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
Binary file not shown.
-101
View File
@@ -1,101 +0,0 @@
{
"keyboardJoysticks": [
{
"axisConfig": [
{
"decKey": 65,
"incKey": 68
},
{
"decKey": 87,
"incKey": 83
},
{
"decKey": 69,
"decayRate": 0.0,
"incKey": 82,
"keyRate": 0.009999999776482582
}
],
"axisCount": 3,
"buttonCount": 4,
"buttonKeys": [
90,
88,
67,
86
],
"povConfig": [
{
"key0": 328,
"key135": 323,
"key180": 322,
"key225": 321,
"key270": 324,
"key315": 327,
"key45": 329,
"key90": 326
}
],
"povCount": 1
},
{
"axisConfig": [
{
"decKey": 74,
"incKey": 76
},
{
"decKey": 73,
"incKey": 75
}
],
"axisCount": 2,
"buttonCount": 4,
"buttonKeys": [
77,
44,
46,
47
],
"povCount": 0
},
{
"axisConfig": [
{
"decKey": 263,
"incKey": 262
},
{
"decKey": 265,
"incKey": 264
}
],
"axisCount": 2,
"buttonCount": 6,
"buttonKeys": [
260,
268,
266,
261,
269,
267
],
"povCount": 0
},
{
"axisCount": 0,
"buttonCount": 0,
"povCount": 0
}
],
"robotJoysticks": [
{
"useGamepad": true
},
{
"guid": "78696e70757401000000000000000000",
"useGamepad": true
}
]
}
-89
View File
@@ -1,89 +0,0 @@
{
"HALProvider": {
"Other Devices": {
"SPARK MAX [5]": {
"header": {
"open": true
}
},
"SPARK MAX [6]": {
"header": {
"open": true
}
},
"Talon FX[9]/Integrated Sensor": {
"header": {
"open": true
}
}
}
},
"NTProvider": {
"types": {
"/FMSInfo": "FMSInfo",
"/LiveWindow/BoomBoom": "Subsystem",
"/LiveWindow/Hood": "Subsystem",
"/LiveWindow/Intake": "Subsystem",
"/LiveWindow/LED": "Subsystem",
"/LiveWindow/Serializer": "Subsystem",
"/LiveWindow/Storage": "Subsystem",
"/LiveWindow/SwerveDrive": "Subsystem",
"/LiveWindow/SwerveModule": "Subsystem",
"/LiveWindow/Turret": "Subsystem",
"/LiveWindow/Ungrouped/DigitalInput[27]": "Digital Input",
"/LiveWindow/Ungrouped/DigitalInput[28]": "Digital Input",
"/LiveWindow/Ungrouped/DigitalInput[29]": "Digital Input",
"/LiveWindow/Ungrouped/DigitalInput[3]": "Digital Input",
"/LiveWindow/Ungrouped/PIDController[1]": "PIDController",
"/LiveWindow/Ungrouped/PIDController[2]": "PIDController",
"/LiveWindow/Ungrouped/PIDController[3]": "PIDController",
"/LiveWindow/Ungrouped/Scheduler": "Scheduler",
"/LiveWindow/Ungrouped/Spark[0]": "Motor Controller",
"/LiveWindow/Ungrouped/Talon FX [14]": "Motor Controller",
"/LiveWindow/Ungrouped/Talon FX [15]": "Motor Controller",
"/LiveWindow/Ungrouped/Talon FX [21]": "Motor Controller",
"/LiveWindow/Ungrouped/Talon FX [22]": "Motor Controller",
"/LiveWindow/Ungrouped/Talon FX [23]": "Motor Controller",
"/LiveWindow/Ungrouped/Talon FX [24]": "Motor Controller",
"/LiveWindow/Ungrouped/Talon FX [2]": "Motor Controller",
"/LiveWindow/Ungrouped/Talon FX [3]": "Motor Controller",
"/LiveWindow/Ungrouped/Talon FX [4]": "Motor Controller",
"/LiveWindow/Ungrouped/Talon FX [5]": "Motor Controller",
"/LiveWindow/Ungrouped/Talon FX [6]": "Motor Controller",
"/LiveWindow/Ungrouped/Talon FX [7]": "Motor Controller",
"/LiveWindow/Ungrouped/Talon FX [8]": "Motor Controller",
"/LiveWindow/Ungrouped/Talon FX [9]": "Motor Controller",
"/LiveWindow/Vision": "Subsystem",
"/LiveWindow/VisionOdometry": "Subsystem",
"/SmartDashboard/Field": "Field2d",
"/SmartDashboard/JVM Memory": "Command",
"/SmartDashboard/Odometry Chooser": "String Chooser",
"/SmartDashboard/Scheduler": "Scheduler",
"/SmartDashboard/SendableChooser[0]": "String Chooser",
"/SmartDashboard/Usable Deploy Space": "Command"
},
"windows": {
"/LiveWindow/SwerveDrive": {
"window": {
"visible": true
}
},
"/SmartDashboard/Scheduler": {
"window": {
"visible": true
}
}
}
},
"NetworkTables": {
"SmartDashboard": {
"Odometry Chooser": {
"open": true
},
"SendableChooser[0]": {
"open": true
},
"open": true
}
}
}
+39 -54
View File
@@ -18,6 +18,7 @@ import edu.wpi.first.wpilibj.XboxController;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.Command;
import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.InstantCommand;
import edu.wpi.first.wpilibj2.command.PrintCommand;
import edu.wpi.first.wpilibj2.command.RunCommand; import edu.wpi.first.wpilibj2.command.RunCommand;
import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup;
import edu.wpi.first.wpilibj2.command.button.JoystickButton; import edu.wpi.first.wpilibj2.command.button.JoystickButton;
@@ -71,42 +72,33 @@ public class RobotContainer {
configureButtonBindings(); configureButtonBindings();
/* Default Commands */ /* Default Commands */
// Swerve Drive with Input // Swerve Drive with Input
m_robotSwerveDrive.setDefaultCommand( m_robotSwerveDrive.setDefaultCommand(
new RunCommand(() -> m_robotSwerveDrive.driveWithInput( new RunCommand(() -> m_robotSwerveDrive.driveWithInput(
getDriverController().getLeftX(), getDriverController().getLeftX(),
getDriverController().getLeftY(), getDriverController().getLeftY(),
//getDriverController().getRightX(),
getDriverController().getRightX(), getDriverController().getRightX(),
getDriverController().getRightY(), getDriverController().getRightY(),
true), true),
m_robotSwerveDrive).withName("Swerve driveWithInput defaultCommand")); m_robotSwerveDrive));
// Intake with Triggers // Intake with Triggers
m_robotIntake.setDefaultCommand( m_robotIntake.setDefaultCommand(
new RunCommand(() -> m_robotIntake.runWithTriggers( new RunCommand(() -> m_robotIntake.runWithTriggers(
getOperatorController().getLeftTriggerAxis(), getOperatorController().getLeftTriggerAxis(),
getOperatorController().getRightTriggerAxis()), getOperatorController().getRightTriggerAxis()),
m_robotIntake).withName("Intake runWithTriggers defaultCommand")); m_robotIntake));
// Storage Management // Storage Management
/*m_robotStorage.setDefaultCommand( // m_robotStorage.setDefaultCommand(new RunCommand(() -> m_robotStorage.manageStorage(), m_robotStorage).withName("Storage manageStorage defaultCommand"));
new RunCommand(() -> m_robotStorage.manageStorage(), // Serializer Management
m_robotStorage).withName("Storage manageStorage defaultCommand"));*/ // m_robotSerializer.setDefaultCommand(new RunCommand(() -> m_robotSerializer.setSerializer(0.8),//m_robotSerializer.setSerializerStateWithBeam(), m_robotSerializer).withName("Serializer setSerializerStateWithBeam defaultCommand"));
// Serializer Management // Turret Manual
// m_robotSerializer.setDefaultCommand( m_robotTurret.setDefaultCommand(new RunCommand(() -> m_robotTurret.runTurretWithInput(getOperatorController().getLeftX()), m_robotTurret));
// new RunCommand(() -> m_robotSerializer.setSerializer(0.8),//m_robotSerializer.setSerializerStateWithBeam(), m_robotHood.setDefaultCommand(new RunCommand(() -> m_robotHood.runHood(getOperatorController().getRightY() * 0.1), m_robotHood));
// m_robotSerializer).withName("Serializer setSerializerStateWithBeam defaultCommand")); // m_robotTurret.setDefaultCommand(new AimToCenter(m_robotTurret, m_robotSwerveDrive, m_robotVisionOdometry));
// Turret Manual
m_robotTurret.setDefaultCommand(
new RunCommand(() -> m_robotTurret.runTurretWithInput(getOperatorController().getLeftX()),
m_robotTurret).withName("Turret runTurretWithInput defaultCommand"));
m_robotHood.setDefaultCommand(
new RunCommand(() -> m_robotHood.runHood(getOperatorController().getRightY() * 0.1), m_robotHood));
// m_robotTurret.setDefaultCommand(
// new AimToCenter(m_robotTurret, m_robotSwerveDrive, m_robotVisionOdometry));
// continually sends updates to the Blinkin LED controller to keep the lights on // continually sends updates to the Blinkin LED controller to keep the lights on
// m_robotLED.setDefaultCommand(new RunCommand(m_robotLED::updateLED, m_robotLED).withName("LED update defaultCommand")); // m_robotLED.setDefaultCommand(new RunCommand(m_robotLED::updateLED, m_robotLED).withName("LED update defaultCommand"));
// Creates a button on the SmartDashboard that will record the path of the robot. // Creates a button on the SmartDashboard that will record the path of the robot.
SmartDashboard.putData("Path Recording", m_pathChooser); SmartDashboard.putData("Path Recording", m_pathChooser);
} }
@@ -118,6 +110,7 @@ public class RobotContainer {
* passing it to a {@link edu.wpi.first.wpilibj2.command.button.JoystickButton}. * passing it to a {@link edu.wpi.first.wpilibj2.command.button.JoystickButton}.
*/ */
private void configureButtonBindings() { private void configureButtonBindings() {
// Iterate over all Xbox controller buttons.
for (XboxController.Button binding : XboxController.Button.values()) { for (XboxController.Button binding : XboxController.Button.values()) {
/* ------------------------------------ Driver ------------------------------------ */ /* ------------------------------------ Driver ------------------------------------ */
JoystickButton button = new JoystickButton(getDriverController(), binding.value); JoystickButton button = new JoystickButton(getDriverController(), binding.value);
@@ -126,13 +119,13 @@ public class RobotContainer {
else if (binding == XboxController.Button.kRightBumper) else if (binding == XboxController.Button.kRightBumper)
/* Right Bumper > Shift Up */ button.whenPressed(() -> m_robotSwerveDrive.highSpeed(true)); /* Right Bumper > Shift Up */ button.whenPressed(() -> m_robotSwerveDrive.highSpeed(true));
else if (binding == XboxController.Button.kLeftStick) else if (binding == XboxController.Button.kLeftStick)
/* Left Stick > Unbound */ {/* No Commands */} /* Left Stick > Unbound */ button.whenPressed(new PrintCommand("Unbound"));
else if (binding == XboxController.Button.kRightStick) else if (binding == XboxController.Button.kRightStick)
/* Right Stick > Unbound */ {/* No Commands */} /* Right Stick > Unbound */ button.whenPressed(new PrintCommand("Unbound"));
else if (binding == XboxController.Button.kA) else if (binding == XboxController.Button.kA)
/* A > Unbound */ {/* No Commands */} /* A > Unbound */ button.whenPressed(new PrintCommand("Unbound"));
else if (binding == XboxController.Button.kB) else if (binding == XboxController.Button.kB)
/* B > Unbound */ {/* No Commands */} /* B > Unbound */ button.whenPressed(new PrintCommand("Unbound"));
else if (binding == XboxController.Button.kX) else if (binding == XboxController.Button.kX)
/* X > TEMP */ button.whenPressed(() -> { /* X > TEMP */ button.whenPressed(() -> {
m_robotMap.leftFront.reset(); m_robotMap.leftFront.reset();
@@ -141,45 +134,37 @@ public class RobotContainer {
m_robotMap.rightBack.reset(); m_robotMap.rightBack.reset();
}); });
else if (binding == XboxController.Button.kY) else if (binding == XboxController.Button.kY)
/* Y > Unbound */ {/* No Commands */} /* Y > Unbound */ button.whenPressed(new PrintCommand("Unbound"));
else if (binding == XboxController.Button.kBack) else if (binding == XboxController.Button.kBack)
/* Start > Reset Odometry */ button.whenPressed(() -> resetOdometry(new Pose2d(0, 0, new Rotation2d(0)))); /* Back > Reset Odometry */ button.whenPressed(() -> resetOdometry(new Pose2d(0, 0, new Rotation2d(0))));
else if (binding == XboxController.Button.kStart) else if (binding == XboxController.Button.kStart)
/* Start > Reset Gyro */ button.whenPressed(m_robotSwerveDrive::resetGyro); /* Start > Reset Gyro */ button.whenPressed(m_robotSwerveDrive::resetGyro);
/* ------------------------------------ Operator ------------------------------------ */ /* ------------------------------------ Operator ------------------------------------ */
button = new JoystickButton(getDriverController(), binding.value); button = new JoystickButton(getDriverController(), binding.value);
if (binding == XboxController.Button.kLeftBumper) if (binding == XboxController.Button.kLeftBumper)
/* Left Bumper > Storage Out */ button /* Left Bumper > Storage Out */ button.whileHeld(() -> m_robotStorage.runStorage(-StorageConstants.STORAGE_SPEED), m_robotStorage)
.whileHeld(() -> m_robotStorage.runStorage(-StorageConstants.STORAGE_SPEED), m_robotStorage) .whenReleased(() -> m_robotStorage.runStorage(0.0), m_robotStorage);
.whenReleased(() -> m_robotStorage.runStorage(0.0), m_robotStorage);
else if (binding == XboxController.Button.kRightBumper) else if (binding == XboxController.Button.kRightBumper)
/* Right Bumper > Storage In */ button /* Right Bumper > Storage In */ button.whileHeld(() -> m_robotStorage.runStorage(StorageConstants.STORAGE_SPEED), m_robotStorage)
.whileHeld(() -> m_robotStorage.runStorage(StorageConstants.STORAGE_SPEED), m_robotStorage) .whenReleased(() -> m_robotStorage.runStorage(0.0), m_robotStorage);
.whenReleased(() -> m_robotStorage.runStorage(0.0), m_robotStorage);
else if (binding == XboxController.Button.kLeftStick) else if (binding == XboxController.Button.kLeftStick)
/* Left Stick > Unbound */ {/* No Commands */} /* Left Stick > Unbound */ button.whenPressed(new PrintCommand("Unbound"));
else if (binding == XboxController.Button.kRightStick) else if (binding == XboxController.Button.kRightStick)
/* Right Stick > Unbound */ {/* No Commands */} /* Right Stick > Unbound */ button.whenPressed(new PrintCommand("Unbound"));
else if (binding == XboxController.Button.kA) else if (binding == XboxController.Button.kA)
// /* A > Shoot with Odo */ // button.whenPressed(new Shoot(m_robotSwerveDrive, m_robotBoomBoom, m_robotTurret, m_robotHood)) /* A > Unbound */ button.whenPressed(new PrintCommand("Unbound"));
/* A > Unbound */ {/* No Commands */}
else if (binding == XboxController.Button.kB) else if (binding == XboxController.Button.kB)
// /* B > Shoot with Lime */ // button.whenPressed(new TrackTarget(m_robotTurret, m_robotBoomBoom, m_robotHood, m_robotSwerveDrive, m_robotVisionOdometry)) /* B > Reset Hood*/ button.whenPressed(new InstantCommand(() -> m_robotHood.m_angleEncoder.setPosition(0)));
/* B > Reset Hood*/
button.whenPressed(new InstantCommand(() -> m_robotHood.m_angleEncoder.setPosition(0)));
else if (binding == XboxController.Button.kX) else if (binding == XboxController.Button.kX)
// /* X > Extend Intake */ // button.whenPressed(() -> m_robotIntake.runExtender(true)) /* X > Run Shooter */ button.whileHeld(() -> m_robotBoomBoom.runDrumShooter(0.3))
/* X > Run Shooter */ button .whenReleased(() -> m_robotBoomBoom.runDrumShooter(0.0));
.whileHeld(() -> m_robotBoomBoom.runDrumShooter(0.3))
.whenReleased(() -> m_robotBoomBoom.runDrumShooter(0.0));
else if (binding == XboxController.Button.kY) else if (binding == XboxController.Button.kY)
// /* Y > Retract Intake */ // operatorButton.whenPressed(() -> m_robotIntake.runExtender(false)) /* Y > Unbound */ button.whenPressed(new PrintCommand("Unbound"));
/* Y > Unbound */ {/* No Commands */}
else if (binding == XboxController.Button.kBack) else if (binding == XboxController.Button.kBack)
/* Back > Unbound */ {/* No Commands */} /* Back > Unbound */ button.whenPressed(new PrintCommand("Unbound"));
else if (binding == XboxController.Button.kStart) else if (binding == XboxController.Button.kStart)
/* Start > Unbound */ {/* No Commands */} /* Start > Unbound */ button.whenPressed(new PrintCommand("Unbound"));
} }
} }
@@ -215,6 +200,10 @@ public class RobotContainer {
return m_driverXbox; return m_driverXbox;
} }
public XboxController getOperatorController() {
return m_operatorXbox;
}
/** /**
* Get odometry. * Get odometry.
* *
@@ -232,8 +221,4 @@ public class RobotContainer {
public void resetOdometry(Pose2d pose) { public void resetOdometry(Pose2d pose) {
m_robotSwerveDrive.resetOdometry(pose); m_robotSwerveDrive.resetOdometry(pose);
} }
public XboxController getOperatorController() {
return m_operatorXbox;
}
} }
+56 -69
View File
@@ -2,8 +2,8 @@ package frc4388.utility;
import static org.fusesource.jansi.Ansi.ansi; import static org.fusesource.jansi.Ansi.ansi;
import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream; import java.io.PrintStream;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
@@ -11,78 +11,64 @@ import java.time.ZoneId;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import java.util.Map; import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.logging.ConsoleHandler;
import java.util.logging.Formatter; import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.LogManager; import java.util.logging.LogManager;
import java.util.logging.LogRecord; import java.util.logging.LogRecord;
import java.util.logging.Logger; 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.Attribute;
import org.fusesource.jansi.Ansi.Color; import org.fusesource.jansi.Ansi.Color;
import org.fusesource.jansi.AnsiConsole; 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() { public static void systemInstall() {
try { try {
// Configure java.util.logging.Logger to output additional colored information. // Configure java.util.logging.Logger to output additional colored information.
LogManager.getLogManager().updateConfiguration(key -> (o, n) -> { LogManager.getLogManager().updateConfiguration(key -> (o, n) -> {
switch (key) { switch (key) {
case ".level": case ".level":
return Level.ALL.getName(); return LEVEL.getName();
case "handlers": case "handlers":
return AnsiColorConsoleHandler.class.getName(); return LoggingAnsiConsoleHandler.class.getName();
default: default:
return n; return n;
} }
}); });
// Replace standard output streams with org.fusesource.jansi.AnsiPrintStreams. // Set the console to process ANSI escape codes.
AnsiConsole.systemInstall(); ANSI_CONSOLE_STREAM.install();
// Replace standard output stream with java.util.logging.Logger. // Sends standard output stream messages through a logger.
System.setOut(printStreamLogger(Logger.getGlobal(), Level.INFO)); System.setOut(printStreamLogger(Logger.getGlobal(), "out", Level.INFO));
// Replace standard error output stream with java.util.logging.Logger. // Sends standard error output stream messages through a logger.
System.setErr(printStreamLogger(Logger.getGlobal(), Level.SEVERE)); System.setErr(printStreamLogger(Logger.getGlobal(), "err", Level.SEVERE));
} catch (IOException exception) { } catch (IOException exception) {
exception.printStackTrace(AnsiConsole.sysErr()); 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 { public static class LoggingAnsiConsoleHandler extends StreamHandler {
@Override public LoggingAnsiConsoleHandler() {
public void publish(LogRecord logRecord) { super(ANSI_CONSOLE_STREAM, new LoggingAnsiFormatter());
AnsiConsole.err().print(getFormatter().format(logRecord)); setLevel(LEVEL);
AnsiConsole.err().flush();
} }
@Override private static class LoggingAnsiFormatter extends Formatter {
public Formatter getFormatter() { private static final ZoneId ZONE_ID = ZoneId.systemDefault();
return formatter; // 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 static String makeStackTraceString(Throwable throwable) {
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) {
StringWriter stringWriter = new StringWriter(); StringWriter stringWriter = new StringWriter();
try (PrintWriter printWriter = new PrintWriter(stringWriter)) { try (PrintWriter printWriter = new PrintWriter(stringWriter)) {
printWriter.println(); printWriter.println();
@@ -93,43 +79,44 @@ public class AnsiLogging extends ConsoleHandler {
@Override @Override
public String format(LogRecord logRecord) { 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. // 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 source = Optional.ofNullable(logRecord.getLoggerName()).or(() -> Optional.ofNullable(logRecord.getSourceClassName())).map(s -> s + " ").orElse("") + Optional.ofNullable(logRecord.getSourceMethodName()).orElse("");
String message = formatMessage(logRecord); String message = formatMessage(logRecord);
// Get the stack trace of the exception if it was thrown. // 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. // 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. // 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();
}
} }
/** private static PrintStream printStreamLogger(Logger logger, String source, Level level) {
* Create a PrintStream that writes to the given logger at the given level return new PrintStream(new ByteArrayOutputStream() {
*
* @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.
*/
@Override @Override
public void write(int i) throws IOException { public void flush() throws IOException {
if (i == '\n') { String s = toString();
logger.log(level, stringBuilder::toString); if (!s.isBlank()) logger.logp(level, null, source, toString());
stringBuilder.setLength(0); reset();
} else stringBuilder.appendCodePoint(i);
} }
}); }, true);
} }
} }