Logging additions 2 (#55)

* Add overload to logger.error() for Throwable to print stack trace

* Replaced all e.printStackTrace() with logger.error()

* Log level dependent on dev or release
This commit is contained in:
Banks T
2020-07-24 12:06:54 -04:00
committed by GitHub
parent 22d7ccc74d
commit 77fd6a84c8
17 changed files with 74 additions and 57 deletions

View File

@@ -40,11 +40,12 @@ public class Main {
public static final int DEFAULT_WEBPORT = 5800;
public static void main(String[] args) {
Logger.setLevel(LogGroup.Camera, LogLevel.TRACE);
Logger.setLevel(LogGroup.WebServer, LogLevel.TRACE);
Logger.setLevel(LogGroup.VisionModule, LogLevel.TRACE);
Logger.setLevel(LogGroup.Data, LogLevel.TRACE);
Logger.setLevel(LogGroup.General, LogLevel.TRACE);
var logLevel = PhotonVersion.isRelease ? LogLevel.ERROR : LogLevel.TRACE;
Logger.setLevel(LogGroup.Camera, logLevel);
Logger.setLevel(LogGroup.WebServer, logLevel);
Logger.setLevel(LogGroup.VisionModule, logLevel);
Logger.setLevel(LogGroup.Data, logLevel);
Logger.setLevel(LogGroup.General, logLevel);
logger.info("Logging initialized!");
@@ -57,8 +58,7 @@ public class Main {
logger.info("Loading native libraries...");
CameraServerCvJNI.forceLoad();
} catch (Exception e) {
logger.error("Failed to load native libraries!");
e.printStackTrace(); // TODO: redirect stacktrace to Logger stream somehow
logger.error("Failed to load native libraries!", e);
}
logger.info("Native libaries loaded.");

View File

@@ -132,14 +132,12 @@ public class ConfigManager {
try {
JacksonUtils.serializer(hardwareConfigFile.toPath(), config.getHardwareConfig());
} catch (IOException e) {
logger.error("Could not save hardware config!");
e.printStackTrace();
logger.error("Could not save hardware config!", e);
}
try {
JacksonUtils.serializer(networkConfigFile.toPath(), config.getNetworkConfig());
} catch (IOException e) {
logger.error("Could not save network config!");
e.printStackTrace();
logger.error("Could not save network config!", e);
}
// save all of our cameras
@@ -172,8 +170,7 @@ public class ConfigManager {
if (pipelineFolder.toFile().exists())
Files.list(pipelineFolder).map(Path::toFile).filter(File::exists).forEach(File::delete);
} catch (IOException e) {
logger.error("Exception while deleting old configs!");
e.printStackTrace();
logger.error("Exception while deleting old configs!", e);
}
for (var pipe : camConfig.pipelineSettings) {
@@ -187,7 +184,7 @@ public class ConfigManager {
try {
JacksonUtils.serializer(pipePath, pipe);
} catch (IOException e) {
logger.error("Could not save " + pipe.pipelineNickname + ".json!");
logger.error("Could not save " + pipe.pipelineNickname + ".json!", e);
}
}
}
@@ -209,7 +206,7 @@ public class ConfigManager {
JacksonUtils.deserialize(
cameraConfigPath.toAbsolutePath(), CameraConfiguration.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
logger.error("Camera config deserialization failed!", e);
}
if (loadedConfig == null) { // If the file could not be deserialized
logger.warn("Could not load camera " + subdir + "'s config.json! Loading " + "default");
@@ -250,8 +247,7 @@ public class ConfigManager {
try {
return JacksonUtils.deserialize(p, CVPipelineSettings.class);
} catch (JsonProcessingException e) {
logger.error("Exception while deserializing " + relativizedFilePath);
e.printStackTrace();
logger.error("Exception while deserializing " + relativizedFilePath, e);
} catch (IOException e) {
logger.warn(
"Could not load pipeline at "
@@ -270,7 +266,7 @@ public class ConfigManager {
loadedConfigurations.put(subdir.toFile().getName(), loadedConfig);
}
} catch (IOException e) {
e.printStackTrace();
logger.error("Error loading camera configs!", e);
}
return loadedConfigurations;
}

View File

@@ -67,8 +67,7 @@ public class DataChangeService {
}
}
} catch (Exception e) {
logger.error("Exception when dispatching event!");
e.printStackTrace();
logger.error("Exception when dispatching event!", e);
}
}
}

View File

@@ -18,6 +18,8 @@
package org.photonvision.common.logging;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Path;
@@ -33,6 +35,7 @@ import org.photonvision.common.dataflow.events.OutgoingUIEvent;
import org.photonvision.server.SocketHandler;
import org.photonvision.server.UIUpdateType;
@SuppressWarnings("unused")
public class Logger {
public static final String ANSI_RESET = "\u001B[0m";
@@ -85,8 +88,8 @@ public class Logger {
return builder.toString();
}
private static HashMap<LogGroup, LogLevel> levelMap = new HashMap<>();
private static List<LogAppender> currentAppenders = new ArrayList<>();
private static final HashMap<LogGroup, LogLevel> levelMap = new HashMap<>();
private static final List<LogAppender> currentAppenders = new ArrayList<>();
static {
levelMap.put(LogGroup.Camera, LogLevel.INFO);
@@ -101,6 +104,7 @@ public class Logger {
currentAppenders.add(new UILogAppender());
}
@SuppressWarnings("ResultOfMethodCallIgnored")
public static void addFileAppender(Path logFilePath) {
var file = logFilePath.toFile();
if (!file.exists()) {
@@ -151,6 +155,11 @@ public class Logger {
log(message, LogLevel.ERROR);
}
public void error(String message, Throwable t) {
log(message, LogLevel.ERROR);
log(convertStackTraceToString(t), LogLevel.ERROR);
}
public void warn(Supplier<String> messageSupplier) {
log(messageSupplier, LogLevel.WARN);
}
@@ -183,6 +192,16 @@ public class Logger {
log(message, LogLevel.TRACE);
}
private static String convertStackTraceToString(Throwable throwable) {
try (StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw)) {
throwable.printStackTrace(pw);
return sw.toString();
} catch (IOException ioe) {
throw new IllegalStateException(ioe);
}
}
private interface LogAppender {
void log(String message, LogLevel level);
}

View File

@@ -61,7 +61,7 @@ public class LinuxNetworking extends SysNetworking {
}
}
} catch (IOException e) {
e.printStackTrace();
logger.error("Failed to set DHCP!", e);
return false;
}
@@ -78,7 +78,7 @@ public class LinuxNetworking extends SysNetworking {
var setHostnameRetCode = shell.execute("hostnamectl", "set-hostname", newHostname);
return setHostnameRetCode == 0;
} catch (Exception e) {
e.printStackTrace();
logger.error("Failed to set hostname!", e);
return false;
}
}
@@ -97,7 +97,7 @@ public class LinuxNetworking extends SysNetworking {
FileUtils.writeLines(dhcpConf, lines);
return true;
} catch (IOException e) {
e.printStackTrace();
logger.error("Failed to set Static IP!", e);
}
return false;
}

View File

@@ -18,9 +18,13 @@
package org.photonvision.common.networking;
import java.net.InterfaceAddress;
import org.photonvision.common.logging.LogGroup;
import org.photonvision.common.logging.Logger;
@SuppressWarnings("WeakerAccess")
public class NetworkInterface {
private static final Logger logger = new Logger(NetworkInterface.class, LogGroup.General);
public final String name;
public final String displayName;
public final String IPAddress;
@@ -68,7 +72,7 @@ public class NetworkInterface {
+ (shiftby & 255);
// return InetAddress.getByName(maskString);
} catch (Exception e) {
e.printStackTrace();
logger.error("Failed to get netmask!", e);
}
// Something went wrong here...
return null;

View File

@@ -39,7 +39,7 @@ public class ScriptEvent {
String error = executor.getError();
if (!error.isEmpty()) {
System.err.printf("Error when running \"%s\" script: %s\n", config.eventType.name(), error);
logger.error("Error when running \"" + config.eventType.name() + "\" script: " + error);
} else if (!output.isEmpty()) {
logger.info(
String.format("Output from \"%s\" script: %s\n", config.eventType.name(), output));

View File

@@ -51,7 +51,7 @@ public class ScriptManager {
TimedTaskManager.getInstance().addTask("ScriptRunner", new ScriptRunner(), 10);
} else {
System.err.println("Something went wrong initializing scripts! Events will not run.");
logger.error("Something went wrong initializing scripts! Events will not run.");
}
}
@@ -61,7 +61,7 @@ public class ScriptManager {
try {
handleEvent(queuedEvents.takeFirst());
} catch (InterruptedException e) {
e.printStackTrace();
logger.error("ScriptRunner queue interrupted!", e);
}
}
@@ -76,9 +76,7 @@ public class ScriptManager {
try {
toRun.run();
} catch (IOException e) {
System.err.printf(
"Failed to run script for event: %s, exception below.\n%s\n",
eventType.name(), e.getMessage());
logger.error("Failed to run script for event \"" + eventType.name() + "\"", e);
}
}
}
@@ -107,7 +105,7 @@ public class ScriptManager {
JacksonUtils.serializer(
scriptConfigPath, eventsConfig.toArray(new ScriptConfig[0]), true);
} catch (IOException e) {
e.printStackTrace();
logger.error("Failed to initialize!", e);
}
}
}
@@ -119,7 +117,7 @@ public class ScriptManager {
return List.of(raw);
}
} catch (IOException e) {
e.printStackTrace();
logger.error("Failed to load scripting config!", e);
}
return new ArrayList<>();
}
@@ -139,7 +137,7 @@ public class ScriptManager {
queuedEvents.putLast(eventType);
logger.info("Queued event: " + eventType.name());
} catch (InterruptedException e) {
System.err.println("Failed to add event to queue: " + eventType.name());
logger.error("Failed to add event to queue: " + eventType.name(), e);
}
}
}

View File

@@ -20,6 +20,8 @@ package org.photonvision.common.util;
import edu.wpi.first.wpiutil.RuntimeDetector;
import java.io.IOException;
import org.apache.commons.lang3.SystemUtils;
import org.photonvision.common.logging.LogGroup;
import org.photonvision.common.logging.Logger;
@SuppressWarnings("unused")
public enum Platform {
@@ -42,6 +44,8 @@ public enum Platform {
this.value = value;
}
private static final Logger logger = new Logger(Platform.class, LogGroup.General);
public static final Platform CurrentPlatform = getCurrentPlatform();
public static boolean isWindows() {
@@ -64,7 +68,7 @@ public enum Platform {
try {
shell.execute("id", null, true, "-u");
} catch (IOException e) {
e.printStackTrace();
logger.error("Failed to perform root check!", e);
}
while (!shell.isOutputCompleted()) {

View File

@@ -22,7 +22,7 @@ import org.photonvision.common.logging.LogGroup;
import org.photonvision.common.logging.Logger;
public final class SerializationUtils {
private static final Logger LOGGER = new Logger(SerializationUtils.class, LogGroup.General);
private static final Logger logger = new Logger(SerializationUtils.class, LogGroup.General);
public static HashMap<String, Object> objectToHashMap(Object src) {
var ret = new HashMap<String, Object>();
@@ -37,8 +37,7 @@ public final class SerializationUtils {
ret.put(field.getName(), ordinal.ordinal());
}
} catch (IllegalArgumentException | IllegalAccessException e) {
LOGGER.error("Could not serialize " + src.getClass().getSimpleName());
e.printStackTrace();
logger.error("Could not serialize " + src.getClass().getSimpleName(), e);
}
}
return ret;

View File

@@ -63,7 +63,7 @@ public class FileUtils {
p.waitFor();
} catch (Exception e) {
e.printStackTrace();
logger.error("Setting perms failed!", e);
}
} else {
logger.info("Cannot set directory permissions on Windows!");

View File

@@ -272,14 +272,12 @@ public class SocketHandler {
break;
}
}
} catch (Exception ex) {
logger.error("unknown booboo");
ex.printStackTrace();
} catch (Exception e) {
logger.error("Failed to parse message!", e);
}
}
} catch (IOException e) {
// TODO: log
e.printStackTrace();
logger.error("Failed to deserialize message!", e);
}
}

View File

@@ -71,8 +71,7 @@ class UIOutboundSubscriber extends DataChangeSubscriber {
}
}
} catch (JsonProcessingException e) {
// TODO: Log
e.printStackTrace();
logger.error("Failed to process outgoing message!", e);
}
}
}

View File

@@ -135,8 +135,7 @@ public class USBCameraSource implements VisionSource {
videoModesList.add(videoMode);
}
} catch (Exception e) {
logger.error("Exception while enumerating video modes!");
e.printStackTrace();
logger.error("Exception while enumerating video modes!", e);
videoModesList = List.of();
}
for (VideoMode videoMode : videoModesList) {

View File

@@ -82,7 +82,7 @@ public class Calibrate3dPipe
stdDeviationsExtrinsics,
perViewErrors);
} catch (Exception e) {
e.printStackTrace();
logger.error("Calibration failed!", e);
}
JsonMat cameraMatrixMat = JsonMat.fromMat(cameraMatrix);
JsonMat distortionCoefficientsMat = JsonMat.fromMat(distortionCoefficients);

View File

@@ -27,6 +27,8 @@ import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.Scalar;
import org.photonvision.common.logging.LogGroup;
import org.photonvision.common.logging.Logger;
import org.photonvision.vision.calibration.CameraCalibrationCoefficients;
import org.photonvision.vision.pipe.CVPipe;
import org.photonvision.vision.target.TargetModel;
@@ -35,6 +37,8 @@ import org.photonvision.vision.target.TrackedTarget;
public class SolvePNPPipe
extends CVPipe<List<TrackedTarget>, List<TrackedTarget>, SolvePNPPipe.SolvePNPPipeParams> {
private static final Logger logger = new Logger(SolvePNPPipe.class, LogGroup.VisionModule);
private final MatOfPoint2f imagePoints = new MatOfPoint2f();
@Override
@@ -68,7 +72,7 @@ public class SolvePNPPipe
rVec,
tVec);
} catch (Exception e) {
e.printStackTrace();
logger.error("Exception when attempting solvePnP!", e);
return;
}

View File

@@ -197,8 +197,7 @@ public class VisionModule {
try {
method.invoke(visionSource.getSettables(), newPropValue);
} catch (Exception e) {
logger.error("Failed to invoke camera settable method: " + method.getName());
e.printStackTrace();
logger.error("Failed to invoke camera settable method: " + method.getName(), e);
}
}
}
@@ -249,11 +248,10 @@ public class VisionModule {
+ " with value "
+ newPropValue
+ " on "
+ currentSettings);
e.printStackTrace();
+ currentSettings,
e);
} catch (Exception e) {
logger.error("Unknown exception when setting PSC prop!");
e.printStackTrace();
logger.error("Unknown exception when setting PSC prop!", e);
}
saveModule();