From 0ea61a059fdacec7cab3141997ee8cf8c5e32f53 Mon Sep 17 00:00:00 2001 From: CoolSpy3 Date: Sun, 8 May 2022 16:47:24 -0700 Subject: [PATCH] remove logging support --- .../lib199/logging/DataLog.java | 197 --------- .../lib199/logging/EventLog.java | 162 -------- .../lib199/logging/GlobalLogInfo.java | 94 ----- .../carlmontrobotics/lib199/logging/Log.java | 391 ------------------ .../lib199/logging/LogFiles.java | 178 -------- .../lib199/logging/LogUtils.java | 123 ------ .../lib199/logging/TimeLog.java | 152 ------- 7 files changed, 1297 deletions(-) delete mode 100644 src/main/java/org/carlmontrobotics/lib199/logging/DataLog.java delete mode 100644 src/main/java/org/carlmontrobotics/lib199/logging/EventLog.java delete mode 100644 src/main/java/org/carlmontrobotics/lib199/logging/GlobalLogInfo.java delete mode 100644 src/main/java/org/carlmontrobotics/lib199/logging/Log.java delete mode 100644 src/main/java/org/carlmontrobotics/lib199/logging/LogFiles.java delete mode 100644 src/main/java/org/carlmontrobotics/lib199/logging/LogUtils.java delete mode 100644 src/main/java/org/carlmontrobotics/lib199/logging/TimeLog.java diff --git a/src/main/java/org/carlmontrobotics/lib199/logging/DataLog.java b/src/main/java/org/carlmontrobotics/lib199/logging/DataLog.java deleted file mode 100644 index 5eddb8c4..00000000 --- a/src/main/java/org/carlmontrobotics/lib199/logging/DataLog.java +++ /dev/null @@ -1,197 +0,0 @@ -package org.carlmontrobotics.lib199.logging; - -import java.io.IOException; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.function.Supplier; - -import org.apache.commons.csv.CSVPrinter; - -import edu.wpi.first.wpilibj.RobotController; -import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; - -/** - * Handles data logging code - * @deprecated Instead use WPILib's Logging API - */ -@Deprecated -final class DataLog { - - private static Object[] dataExportBuffer = null; - private static ArrayList varIds = new ArrayList<>(); - private static HashMap types = new HashMap<>(); - private static HashMap data = new HashMap<>(); - private static HashMap> dataSuppliers = new HashMap<>(); - private static long refFGATime; - private static boolean isDisabled = false; - - /** - * Initializes the data logging code and prints variable ids to the csv file or returns if it has already been initialized - */ - static void init(LocalDateTime time, long refFGATime) { - if(!GlobalLogInfo.isInit()) { - return; - } - DataLog.refFGATime = refFGATime; - registerVarBypassErrors(VarType.DOUBLE, "Seconds Since: " + time.format(GlobalLogInfo.dateTimeFormat), () -> ((double)((RobotController.getFPGATime()-DataLog.refFGATime)/1000))/1000); - try { - CSVPrinter printer = GlobalLogInfo.getDataPrinter(); - printer.printRecord(varIds.toArray()); - } catch(IOException e) { - LogUtils.handleLoggingError(false, "printing csv headers", e); - } - } - - /** - * Registers a variable to be logged whenever {@link #logData()} is called. Must be called before {@link #init()} - * @param type The {@link VarType} of the variable - * @param id The id to associate with the variable - * @param supplier The {@link Supplier} that will be used to load the variable data when {@link #fetchData()} is called - * @throws IllegalArgumentException If the provided variable id has already been registered - * @throws IllegalStateException If the data logging code has already been initialized - */ - static void registerVar(VarType type, String id, Supplier supplier) throws IllegalArgumentException, IllegalStateException { - LogUtils.checkNotInit(); - if(varIds.contains(id)) { - throw new IllegalArgumentException("Variable is already registered"); - } - varIds.add(id); - types.put(id, type); - dataSuppliers.put(id, supplier); - } - - private static void registerVarBypassErrors(VarType type, String id, Supplier supplier) { - if(!varIds.contains(id)) { - varIds.add(0, id); - } - types.put(id, type); - dataSuppliers.put(id, supplier); - } - - /** - * Fetches variable data and then prints it to the csv file and {@link SmartDashboard} - * @throws IllegalStateException If the data logging code is not initialized - */ - static void logData() throws IllegalStateException { - LogUtils.checkInit(); - fetchData(); - if(!isDisabled) { - TimeLog.startDataLogCycle(); - try { - CSVPrinter printer = GlobalLogInfo.getDataPrinter(); - printer.printRecord((Object[])exportData()); - } catch(IOException e) { - LogUtils.handleLoggingError(false, "writing data", e); - } - TimeLog.endDataLogCycle(); - } - putSmartDashboardData(); - } - - /** - * Fetches data from the {@link Supplier}s and puts it into a {@link HashMap} accessable from {@link #getData()} - * @throws IllegalStateException If the data logging code is not yet initialized - */ - static void fetchData() throws IllegalStateException { - LogUtils.checkInit(); - TimeLog.startDataFetchCycle(); - for(String id: varIds) { - data.put(id, dataSuppliers.get(id).get()); - } - TimeLog.endDataFetchCycle(); - } - - private static Object[] exportData() { - if(dataExportBuffer == null) { - dataExportBuffer = new Object[varIds.size()]; - } - for(int i = 0; i < varIds.size(); i++) { - dataExportBuffer[i] = data.get(varIds.get(i)); - } - return dataExportBuffer; - } - - /** - * Puts the last set of fetched data to {@link SmartDashboard} or fetches new data if none has been fetched yet - * @throws IllegalStateException If new data has to be fetched and the data logging api has not been initialized - */ - static void putSmartDashboardData() throws IllegalStateException { - if(data.size() != varIds.size()) { - fetchData(); - } - for(int i = 1; i < varIds.size(); i++) { - String id = varIds.get(i); - try { - switch(types.get(id)) { - case BOOLEAN: - SmartDashboard.putBoolean(id, (Boolean)data.get(id)); - break; - case INTEGER: - SmartDashboard.putNumber(id, (Integer)data.get(id)); - break; - case DOUBLE: - SmartDashboard.putNumber(id, (Double)data.get(id)); - break; - case STRING: - SmartDashboard.putString(id, (String)data.get(id)); - break; - } - } catch(Exception e) {} - } - } - - /** - * @return An {@link ArrayList} containing the ids of all registered variabless - */ - static ArrayList getVarIds() { - return new ArrayList<>(varIds); - } - - /** - * @return A {@link HashMap} mapping all registered variable ids to their respective {@link VarType} - */ - static HashMap getTypes() { - return new HashMap<>(types); - } - - /** - * @return A {@link HashMap} mapping all registered variable ids to their last fetched value or an empty map if data has not yet been fetched - */ - static HashMap getData() { - return new HashMap<>(data); - } - - /** - * Flushes the data log - */ - static void flush() { - try { - GlobalLogInfo.getDataPrinter().flush(); - } catch(IOException e) { - System.err.println("Error flushing data file."); - System.err.println("Full stack trace:"); - e.printStackTrace(System.err); - } - } - - /** - * @return Whether data logging has been disabled by the user - * @see #setDisabled(boolean) - */ - static boolean getDisabled() { - return isDisabled; - } - - /** - * Sets whether data logging should be disabled - * @param disabled The current disabled state - * @see #getDisabled() - */ - static void setDisabled(boolean disabled) { - isDisabled = disabled; - } - - private DataLog() {} - -} \ No newline at end of file diff --git a/src/main/java/org/carlmontrobotics/lib199/logging/EventLog.java b/src/main/java/org/carlmontrobotics/lib199/logging/EventLog.java deleted file mode 100644 index e6db0bb7..00000000 --- a/src/main/java/org/carlmontrobotics/lib199/logging/EventLog.java +++ /dev/null @@ -1,162 +0,0 @@ -package org.carlmontrobotics.lib199.logging; - -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.util.logging.ErrorManager; -import java.util.logging.FileHandler; -import java.util.logging.Handler; -import java.util.logging.Level; -import java.util.logging.LogRecord; -import java.util.logging.Logger; -import java.util.logging.SimpleFormatter; - -/** - * Handles event logging code - * @deprecated Instead use WPILib's Logging API - */ -@Deprecated -final class EventLog { - - private static Logger logger; - private static Handler handler; - private static ErrorManager errorManager; - - static { - logger = Logger.getLogger("RobotLogger"); - logger.setUseParentHandlers(false); - logger.setLevel(Level.INFO); - errorManager = new ErrorManager() { - @Override - public synchronized void error(String msg, Exception ex, int code) { - EventLog.error(msg, ex, code); - } - }; - } - - /** - * Initializes the event logging code or returns if it has already been initialized - */ - static void init() { - if(!GlobalLogInfo.isInit()) { - return; - } - try { - handler = new FileHandler(GlobalLogInfo.getEventFile().getAbsolutePath(), false); - handler.setErrorManager(errorManager); - handler.setFormatter(new LogFormatter()); - logger.addHandler(handler); - } catch(IOException e) { - LogUtils.handleLoggingError(true, "setting up event log handler", e); - } - } - - /** - * Sets the lowest {@link Level} of message to log - * @param level The {@link Level} to set as the minumum - */ - static void setLoggingLevel(Level level) { - logger.setLevel(level); - } - - /** - * Logs a message to the log file - * @param message The message to log - * @param level The level at which to log the message - * @throws IllegalStateException If the event logging code is not yet initialized - */ - static void log(String message, Level level) throws IllegalStateException { - LogUtils.checkInit(); - TimeLog.startEventLogCycle(); - logger.log(level, message); - TimeLog.endEventLogCycle(); - } - - /** - * Logs an {@link Throwable} to the log file - * @param message The message to log with the {@link Throwable}. This will be replaced with {@link Throwable#getMessage()} if null or "" - * @param error The {@link Throwable} to log - * @throws IllegalStateException If the event logging code is not yet initialized - */ - static void logException(String message, Throwable error) throws IllegalStateException { - LogUtils.checkInit(); - message = message == null || message.isEmpty() ? error.getMessage() : message; - TimeLog.startEventLogCycle(); - logger.log(Level.SEVERE, message, error); - TimeLog.endEventLogCycle(); - } - - private static synchronized void error(String msg, Exception ex, int code) { - String task; - switch(code) { - case ErrorManager.OPEN_FAILURE: - task = "while opening an output stream"; - break; - case ErrorManager.CLOSE_FAILURE: - task = "while closing an output stream"; - break; - case ErrorManager.FLUSH_FAILURE: - task = "while flushing an output stream"; - break; - case ErrorManager.FORMAT_FAILURE: - task = "while formatting a message"; - break; - case ErrorManager.GENERIC_FAILURE: - default: - task = "of type GENERIC_FAILURE"; - break; - } - String message = task + (msg != null ? " with message " + msg : ""); - LogUtils.handleLoggingError(true, message, ex); - } - - /** - * Flushes the event log - */ - static void flush() { - handler.flush(); - } - - private EventLog() {} - - private static final class LogFormatter extends SimpleFormatter { - - private final String format = "%1$tH:%1$tM:%1$tS.%1$tL %4$s: %5$s%6$s%n"; - - @Override - public String format(LogRecord record) { - ZonedDateTime zdt = ZonedDateTime.ofInstant( - record.getInstant(), ZoneId.systemDefault()); - String source; - if (record.getSourceClassName() != null) { - source = record.getSourceClassName(); - if (record.getSourceMethodName() != null) { - source += " " + record.getSourceMethodName(); - } - } else { - source = record.getLoggerName(); - } - String message = formatMessage(record); - String throwable = ""; - if (record.getThrown() != null) { - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - pw.println(); - record.getThrown().printStackTrace(pw); - pw.close(); - throwable = sw.toString(); - } - return String.format(format, - zdt, - source, - record.getLoggerName(), - record.getLevel().getLocalizedName(), - message, - throwable); - } - - } - -} \ No newline at end of file diff --git a/src/main/java/org/carlmontrobotics/lib199/logging/GlobalLogInfo.java b/src/main/java/org/carlmontrobotics/lib199/logging/GlobalLogInfo.java deleted file mode 100644 index 421c5600..00000000 --- a/src/main/java/org/carlmontrobotics/lib199/logging/GlobalLogInfo.java +++ /dev/null @@ -1,94 +0,0 @@ -package org.carlmontrobotics.lib199.logging; - -import java.io.File; -import java.time.format.DateTimeFormatter; - -import org.apache.commons.csv.CSVPrinter; - -/** - * Stores global information about the state of the logging code - * @deprecated Instead use WPILib's Logging API - */ -@Deprecated -public final class GlobalLogInfo { - - private static boolean isInit, areEventsDisabled, isDataDisabled; - private static File eventFile, dataFile; - private static CSVPrinter dataPrinter; - public static final DateTimeFormatter dateTimeFormat = DateTimeFormatter.ofPattern("HH:mm:ss.SSS"); - - /** - * @return Whether the logging code has been initialized - */ - public static boolean isInit() { - return isInit; - } - - /** - * @return Whether event logging code has been disabled - */ - public static boolean areEventsDisabled() { - return areEventsDisabled; - } - - /** - * @return Whether data logging code has been disabled - */ - public static boolean isDataDisabled() { - return isDataDisabled; - } - - /** - * @return The {@link File} to which events are being logged - */ - public static File getEventFile() { - return eventFile; - } - - /** - * @return The {@link File} to which data is being logged - */ - public static File getDataFile() { - return dataFile; - } - - /** - * @return The {@link CSVPrinter} being used to log data - */ - static CSVPrinter getDataPrinter() { - return dataPrinter; - } - - /** - * Disables event logging - */ - static void disableEvents() { - areEventsDisabled = true; - } - - /** - * Disables data logging - */ - static void disableData() { - isDataDisabled = true; - } - - /** - * Initializes the required global data as well as {@EventLog} and {@link DataLog} or returns if it has already been initialized - * @param eventFile The {@link File} to which events will be logged - * @param dataFile The {@link File} to which data will be logged - * @param dataPrinter The {@link CSVPrinter} to use to log data - */ - static void init(File eventFile, File dataFile, CSVPrinter dataPrinter) { - if(isInit()) { - return; - } - GlobalLogInfo.eventFile = eventFile; - GlobalLogInfo.dataFile = dataFile; - GlobalLogInfo.dataPrinter = dataPrinter; - isInit = true; - } - - private GlobalLogInfo() {} - -} \ No newline at end of file diff --git a/src/main/java/org/carlmontrobotics/lib199/logging/Log.java b/src/main/java/org/carlmontrobotics/lib199/logging/Log.java deleted file mode 100644 index 33555b8b..00000000 --- a/src/main/java/org/carlmontrobotics/lib199/logging/Log.java +++ /dev/null @@ -1,391 +0,0 @@ -package org.carlmontrobotics.lib199.logging; - -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.function.Supplier; -import java.util.logging.Level; - -import org.apache.commons.csv.CSVFormat; - -import edu.wpi.first.wpilibj.RobotController; -import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; - -/** - * Provides an interface through which to access the logging code - * @deprecated Instead use WPILib's Logging API - */ -@Deprecated -public final class Log { - - private static int step = 0, interval = 1; - - /** - * Initializes the logging code to log data with {@link CSVFormat#DEFAULT}. This is the same as calling Log.init(CSVFormat.DEFAULT) - * @see #init(CSVFormat) - */ - public static void init() { - init(CSVFormat.DEFAULT); - } - - /** - * Initializes the logging code - * @param dataFormat The {@link CSVFormat} to use when logging data - * @throws IllegalStateException If the logging code is already initialized - * @see #init() - */ - public static void init(CSVFormat dataFormat) throws IllegalStateException { - try { - LocalDateTime time = LocalDateTime.now(); - LogUtils.checkNotInit(); - LogFiles.init(dataFormat, time); - EventLog.init(); - DataLog.init(time, RobotController.getFPGATime()); - } catch(IllegalStateException e) { - LogUtils.handleException(e); - } - } - - //Event Logging Code - /** - * Logs an {@link Throwable} to the log file. This is the same as Log.logException(null, cause) - * @param cause The {@link Throwable} to log - * @see #logException(String, Throwable) - */ - public static void logException(Throwable cause) { - if(GlobalLogInfo.areEventsDisabled()) { - return; - } - try { - LogUtils.checkInit(); - logException(null, cause); - } catch(IllegalStateException e) { - LogUtils.handleException(e); - } - } - - /** - * Logs an {@link Throwable} to the log file - * @param message The message to log with the {@link Throwable}. This will be replaced with {@link Throwable#getMessage()} if null or "" - * @param cause The {@link Throwable} to log - * @see #logException(Throwable) - */ - public static void logException(String message, Throwable cause) { - if(GlobalLogInfo.areEventsDisabled()) { - return; - } - try { - LogUtils.checkInit(); - EventLog.logException(message, cause); - } catch(IllegalStateException e) { - LogUtils.handleException(e); - } - } - - /** - * Logs an error message to the log file - * @param message The error message to log - * @see #logWarningMessage(String) - * @see #logInfoMessage(String) - * @see #logConfigMessage(String) - */ - public static void logErrorMessage(String message) { - if(GlobalLogInfo.areEventsDisabled()) { - return; - } - try { - LogUtils.checkInit(); - EventLog.log(message, Level.SEVERE); - } catch(IllegalStateException e) { - LogUtils.handleException(e); - } - } - - /** - * Logs a warning message to the log file - * @param message The warning message to log - * @see #logErrorMessage(String) - * @see #logInfoMessage(String) - * @see #logConfigMessage(String) - */ - public static void logWarningMessage(String message) { - if(GlobalLogInfo.areEventsDisabled()) { - return; - } - try { - LogUtils.checkInit(); - EventLog.log(message, Level.WARNING); - } catch(IllegalStateException e) { - LogUtils.handleException(e); - } - } - - /** - * Logs a info message to the log file - * @param message The info message to log - * @see #logErrorMessage(String) - * @see #logWarningMessage(String) - * @see #logConfigMessage(String) - */ - public static void logInfoMessage(String message) { - if(GlobalLogInfo.areEventsDisabled()) { - return; - } - try { - LogUtils.checkInit(); - EventLog.log(message, Level.INFO); - } catch(IllegalStateException e) { - LogUtils.handleException(e); - } - } - - /** - * Logs a config message to the log file - * @param message The config message to log - * @see #logErrorMessage(String) - * @see #logWarningMessage(String) - * @see #logInfoMessage(String) - */ - public static void logConfigMessage(String message) { - if(GlobalLogInfo.areEventsDisabled()) { - return; - } - try { - LogUtils.checkInit(); - EventLog.log(message, Level.CONFIG); - } catch(IllegalStateException e) { - LogUtils.handleException(e); - } - } - - /** - * Sets the lowest {@link Level} of message to log - * @param level The {@link Level} to set as the minumum - */ - public static void setLoggingLevel(Level level) { - if(GlobalLogInfo.areEventsDisabled()) { - return; - } - EventLog.setLoggingLevel(level); - } - - /** - * Turns off event logging temporarily to be restored with an appropriate call to {@link #setLoggingLevel(Level)}. This is the same as calling Log.setLoggingLevel(Level.OFF) - */ - public static void disableEventLogging() { - if(GlobalLogInfo.areEventsDisabled()) { - return; - } - setLoggingLevel(Level.OFF); - } - - //Data Logging Code - private static Supplier createSupplier(Supplier supplier) { - return () -> supplier.get(); - } - - /** - * Registers a boolean variable to be logged - * @param id The id to associate with the variable - * @param supplier The {@link Supplier} that will be used to load the variable data when {@link DataLog#fetchData()} is called - * @see #registerIntegerVar(String, Supplier) - * @see #registerDoubleVar(String, Supplier) - * @see #registerStringVar(String, Supplier) - */ - public static void registerBooleanVar(String id, Supplier supplier) { - if(GlobalLogInfo.isDataDisabled()) { - return; - } - try { - LogUtils.checkNotInit(); - DataLog.registerVar(VarType.BOOLEAN, id, createSupplier(supplier)); - } catch(IllegalArgumentException | IllegalStateException e) { - LogUtils.handleException(e); - } - } - - /** - * Registers an integer variable to be logged - * @param id The id to associate with the variable - * @param supplier The {@link Supplier} that will be used to load the variable data when {@link DataLog#fetchData()} is called - * @see #registerBooleanVar(String, Supplier) - * @see #registerDoubleVar(String, Supplier) - * @see #registerStringVar(String, Supplier) - */ - public static void registerIntegerVar(String id, Supplier supplier) { - if(GlobalLogInfo.isDataDisabled()) { - return; - } - try { - LogUtils.checkNotInit(); - DataLog.registerVar(VarType.INTEGER, id, createSupplier(supplier)); - } catch(IllegalArgumentException | IllegalStateException e) { - LogUtils.handleException(e); - } - } - - /** - * Registers a double variable to be logged - * @param id The id to associate with the variable - * @param supplier The {@link Supplier} that will be used to load the variable data when {@link DataLog#fetchData()} is called - * @see #registerBooleanVar(String, Supplier) - * @see #registerIntegerVar(String, Supplier) - * @see #registerStringVar(String, Supplier) - */ - public static void registerDoubleVar(String id, Supplier supplier) { - if(GlobalLogInfo.isDataDisabled()) { - return; - } - try { - LogUtils.checkNotInit(); - DataLog.registerVar(VarType.DOUBLE, id, createSupplier(supplier)); - } catch(IllegalArgumentException | IllegalStateException e) { - LogUtils.handleException(e); - } - } - - /** - * Registers a string variable to be logged - * @param id The id to associate with the variable - * @param supplier The {@link Supplier} that will be used to load the variable data when {@link #fetchData()} is called - * @see #registerBooleanVar(String, Supplier) - * @see #registerIntegerVar(String, Supplier) - * @see #registerDoubleVar(String, Supplier) - */ - public static void registerStringVar(String id, Supplier supplier) { - if(GlobalLogInfo.isDataDisabled()) { - return; - } - try { - LogUtils.checkNotInit(); - DataLog.registerVar(VarType.STRING, id, createSupplier(supplier)); - } catch(IllegalArgumentException | IllegalStateException e) { - LogUtils.handleException(e); - } - } - - /** - * Fetches data from the {@link Supplier}s and puts it into a {@link HashMap} accessable from {@link #getData()} - * @throws IllegalStateException If the data logging code is not yet initialized - */ - public static void fetchData() { - if(GlobalLogInfo.isDataDisabled()) { - return; - } - try { - LogUtils.checkInit(); - DataLog.fetchData(); - } catch(IllegalStateException e) { - LogUtils.handleException(e); - } - } - - /** - * @return An {@link ArrayList} containing the ids of all registered variabless - */ - public static ArrayList getVarIds() { - return DataLog.getVarIds(); - } - - /** - * @return A {@link HashMap} mapping all registered variable ids to their respective {@link VarType} - */ - public static HashMap getVarTypes() { - return DataLog.getTypes(); - } - - /** - * @return A {@link HashMap} mapping all registered variable ids to their last fetched value or an empty map if data has not yet been fetched - */ - public static HashMap getData() { - return DataLog.getData(); - } - - /** - * Puts the last set of fetched data to {@link SmartDashboard} or fetches new data if none has been fetched yet - */ - public static void putDataToSmartDashboard() { - if(GlobalLogInfo.isDataDisabled()) { - return; - } - try { - LogUtils.checkInit(); - DataLog.putSmartDashboardData(); - } catch(IllegalStateException e) { - LogUtils.handleException(e); - } - } - - /** - * @return The data logging interval - * @see #setDataLogInterval(int) - * @see #logData() - */ - public static int getDataLogInterval() { - return interval; - } - - /** - * Sets how often data should be logged - * @param interval The interval with which data should be logged - * @see #getDataLogInterval() - * @see #logData() - */ - public static void setDataLogInterval(int interval) { - Log.interval = (interval < 1 ? 1 : interval); - } - - /** - * Logs data to the data file or returns if determined by the data logging interval where each interval unit represents one logData call - * @see #getDataLogInterval() - * @see #setDataLogInterval(int) - */ - public static void logData() { - if(GlobalLogInfo.isDataDisabled()) { - return; - } - try { - LogUtils.checkInit(); - if(step == 0) { - DataLog.logData(); - } - step++; - step = step >= interval ? 0 : step; - } catch(IllegalStateException e) { - LogUtils.handleException(e); - } - } - - /** - * @return Whether data logging has been disabled by the user - * @see #setDataLoggingDisabled(boolean) - */ - public static boolean getDataLoggingDisabled() { - return DataLog.getDisabled(); - } - - /** - * Sets whether data logging should be disabled - * @param disabled The current disabled state - * @see #getDataLoggingDisabled() - */ - public static void setDataLoggingDisabled(boolean disabled) { - DataLog.setDisabled(disabled); - } - - /** - * Flushes data to the log files - */ - public static void flush() { - try { - LogUtils.checkInit(); - EventLog.flush(); - DataLog.flush(); - } catch(IllegalStateException e) { - LogUtils.handleException(e); - } - } - - private Log() {} - -} diff --git a/src/main/java/org/carlmontrobotics/lib199/logging/LogFiles.java b/src/main/java/org/carlmontrobotics/lib199/logging/LogFiles.java deleted file mode 100644 index 26c06bfe..00000000 --- a/src/main/java/org/carlmontrobotics/lib199/logging/LogFiles.java +++ /dev/null @@ -1,178 +0,0 @@ -package org.carlmontrobotics.lib199.logging; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.StandardCopyOption; -import java.time.LocalDateTime; -import java.util.ArrayList; - -import org.apache.commons.csv.CSVFormat; -import org.apache.commons.csv.CSVPrinter; - -import edu.wpi.first.wpilibj.DriverStation; - -/** - * Creates the required log files and initializes logging code - * @deprecated Instead use WPILib's Logging API - */ -@Deprecated -final class LogFiles { - - private static int logId; - private static ArrayList existingLogIds; - private static String dirString = System.getProperty("user.home") + "/riologs"; - private static File dirFile, infoFile, infoBackupFile; - - /** - * Initializes the logging code or returns if it is already initialized - * @param dataFormat The {@link CSVFormat} to use when logging data - */ - static void init(CSVFormat dataFormat, LocalDateTime time) { - if(GlobalLogInfo.isInit()) { - return; - } - dirFile = new File(dirString); - dirFile.mkdir(); - infoFile = new File(dirString + "/info.txt"); - infoBackupFile = new File(dirString + "/infobkup.txt"); - try { - infoFile.createNewFile(); - infoBackupFile.createNewFile(); - } catch(IOException e) { - LogUtils.handleLoggingApiDisableError("creating info file", e); - return; - } - existingLogIds = new ArrayList<>(); - try { - backupInfoFile(); - findExistingLogIds(); - clearOldLogs(); - findLogId(); - createLogFiles(dataFormat, time); - } catch(AbortException e) { - LogUtils.handleLoggingApiDisableError(e.getMessage(), (Exception)e.getCause()); - return; - } - } - - private static void backupInfoFile() throws AbortException { - try { - Files.copy(infoFile.toPath(), infoBackupFile.toPath(), StandardCopyOption.REPLACE_EXISTING); - } catch(IOException e) { - throw new AbortException("copying info file", e); - } - } - - private static void findExistingLogIds() { - existingLogIds.clear(); - File[] files = dirFile.listFiles(); - for(File file: files) { - String name = file.getName(); - if(name.indexOf(".") == -1) { - continue; - } - String idString = file.getName().substring(0, name.indexOf(".")); - try { - int id = Integer.parseInt(idString); - if(!existingLogIds.contains(id)) { - existingLogIds.add(id); - } - } catch(NumberFormatException e) { - continue; - } - } - } - - private static void clearOldLogs() throws AbortException { - int lines = 0; - ArrayList linesD = new ArrayList<>(); - try(BufferedReader br = new BufferedReader(new FileReader(infoFile))) { - String line; - while((line = br.readLine()) != null) { - try { - int id = Integer.parseInt(line.substring(0, line.indexOf(" "))); - if(!existingLogIds.contains(id)) { - continue; - } - linesD.add(line); - lines++; - } catch(Exception e) {} - } - } catch(IOException e) { - throw new AbortException("reading info file", e); - } - int endIdx = lines - 100; - if(lines > 100) { - try(BufferedWriter bw = new BufferedWriter(new FileWriter(infoFile))) { - for(int i = endIdx+1; i < lines; i++) { - bw.append(linesD.get(i)); - bw.newLine(); - } - } catch(IOException e) { - throw new AbortException("writing info file", e); - } - for(int i = 0; i < endIdx+1; i++) { - try { - int id = Integer.parseInt(linesD.get(i).substring(0, linesD.get(i).indexOf(" "))); - new File(dirString + "/" + id + ".txt").delete(); - new File(dirString + "/" + id + ".csv").delete(); - existingLogIds.remove(id); - } catch(Exception e) {} - } - } - } - - private static void findLogId() { - for(int id = 0; id < Integer.MAX_VALUE; id++) { - if(!existingLogIds.contains(id)) { - logId = id; - return; - } - } - throw new IllegalStateException("No avaliable log id. If this error occures please verify your instalation as this should not be possible."); - } - - private static void createLogFiles(CSVFormat dataFormat, LocalDateTime time) throws AbortException { - try { - File txtFile = new File(dirString + "/" + logId + ".txt"); - File csvFile = new File(dirString + "/" + logId + ".csv"); - txtFile.createNewFile(); - csvFile.createNewFile(); - try(BufferedWriter bw = new BufferedWriter(new FileWriter(infoFile, true))) { - bw.append(logId + " "); - bw.append(getLogTitle(time)); - bw.newLine(); - } - GlobalLogInfo.init(txtFile, csvFile, new CSVPrinter(new FileWriter(csvFile), dataFormat)); - } catch(IOException e) { - throw new AbortException("creating log files", e); - } - } - - private static String getLogTitle(LocalDateTime currentTime) { - DriverStation.MatchType type = DriverStation.getMatchType(); - String time = currentTime.format(GlobalLogInfo.dateTimeFormat); - if(type == DriverStation.MatchType.None) { - return time; - } - return time + " " + type.toString() + " " + DriverStation.getMatchNumber() + "-" + DriverStation.getReplayNumber(); - } - - private LogFiles() {} - - private static final class AbortException extends Exception { - - private static final long serialVersionUID = 6982175248059420129L; - - public AbortException(String message, Exception cause) { - super(message, cause); - } - - } - -} \ No newline at end of file diff --git a/src/main/java/org/carlmontrobotics/lib199/logging/LogUtils.java b/src/main/java/org/carlmontrobotics/lib199/logging/LogUtils.java deleted file mode 100644 index 614a7d7d..00000000 --- a/src/main/java/org/carlmontrobotics/lib199/logging/LogUtils.java +++ /dev/null @@ -1,123 +0,0 @@ -package org.carlmontrobotics.lib199.logging; - -import static org.carlmontrobotics.lib199.logging.GlobalLogInfo.*; - -/** - * Various utility methods utilized by the logging code - * @deprecated Instead use WPILib's Logging API - */ -@Deprecated -final class LogUtils { - - /** - * Checks that the logging api is initialized - * @throws IllegalStateException If the logging code is not initialized - * @see #checkNotInit() - */ - static void checkInit() throws IllegalStateException { - if(!isInit()) { - throw new IllegalStateException("Logging code is not initialized"); - } - } - - /** - * Checks that the logging api is not initialized - * @throws IllegalStateException If the logging code is already initialized - * @see #checkInit() - */ - static void checkNotInit() throws IllegalStateException { - if(GlobalLogInfo.isInit()) { - throw new IllegalStateException("Logging code already initialized"); - } - } - - /** - * Handles an {@link Exception} in the logging code by notifying the user and disabling the corresponding sector of code - * @param sector The sector to disable. true for event logging, and false for data logging - * @param task A string representing the task that caused the error to occur - * @param error The {@link Exception} that occured or null if the exception could not be obtained - * @see #handleLoggingApiDisableError(String, Exception) - */ - static void handleLoggingError(boolean sector, String task, Exception error) { - if(sector) { - System.err.println("Error occured while " + task + ". Logging will continue to run with event logging disabled."); - if(error != null) { - System.err.println("Full stack trace:"); - error.printStackTrace(System.err); - } - disableEvents(); - } else { - System.err.println("Error occured while " + task + " logging will continue to run with data logging disabled."); - if(error != null) { - System.err.println("Full stack trace:"); - error.printStackTrace(System.err); - } - disableData(); - } - } - - /** - * Handles an {@link Exception} in the logging code that causes the failure of all of the logging code by notifying the user and disabling the logging code - * @param task A string representing the task that caused the error to occur - * @param error The {@link Exception} that occured or null if the exception could not be obtained - * @see #handleLoggingError(boolean, String, Exception) - */ - static void handleLoggingApiDisableError(String task, Exception error) { - System.err.println("Error occured while " + task + ". Logging will be disabled."); - if(error != null) { - System.err.println("Full stack trace:"); - error.printStackTrace(System.err); - } - disableEvents(); - disableData(); - } - - /** - * Handles an {@link Exception} caused by an illegal operation by the user by notifying the user - * @param e The {@link Exception} to handle - */ - static void handleException(Exception e) { - System.err.print("An Exception occurred in logging code"); - if(e == null) { - System.err.println(". No relevent information regarding the error could be obtained. " - + "IsInit=" + GlobalLogInfo.isInit() + " " + getStateMessage()); - return; - } - StackTraceElement thrower = e.getStackTrace()[0]; - StackTraceElement caller = findCaller(e.getStackTrace()); - System.err.print(": " + e.getClass().getName() + ": " + e.getMessage() + ". The error originated in: " + formatElement(thrower) + ". "); - if(caller == null) { - System.err.print("No infornmation could be obtained about the caller that caused this error."); - } else { - System.err.print("Which was called by: " + formatElement(caller) + ". "); - } - System.err.println(getStateMessage()); - System.err.println("Full stack trace:"); - e.printStackTrace(System.err); - } - - private static StackTraceElement findCaller(StackTraceElement[] stack) { - for(StackTraceElement e: stack) { - if(!e.getClassName().substring(0, e.getClassName().lastIndexOf(".") == -1 ? 0 : e.getClassName().lastIndexOf(".")).equals(LogUtils.class.getPackageName())) { - return e; - } - } - return null; - } - - private static String formatElement(StackTraceElement e) { - return e.getClassName() + " on line: " + e.getLineNumber(); - } - - private static String getStateMessage() { - if(isInit()) { - return "You should try moving the offending method to before Log.init(). "; - } else { - - return "You should try moving the offending method to after Log.init(). "; - } - } - - private LogUtils() {} - -} \ No newline at end of file diff --git a/src/main/java/org/carlmontrobotics/lib199/logging/TimeLog.java b/src/main/java/org/carlmontrobotics/lib199/logging/TimeLog.java deleted file mode 100644 index 5acb05d4..00000000 --- a/src/main/java/org/carlmontrobotics/lib199/logging/TimeLog.java +++ /dev/null @@ -1,152 +0,0 @@ -package org.carlmontrobotics.lib199.logging; - -import java.util.ArrayList; - -import edu.wpi.first.wpilibj.RobotController; - -/** - * Keeps track of the time spent on different sections of the logging code - * @deprecated Instead use WPILib's Logging API - */ -@Deprecated -public final class TimeLog { - - private static long eventStart, dataFetchStart, dataLogStart; - private static double eventMax, eventAvg, dataFetchMax, dataFetchAvg, dataLogMax, dataLogAvg; - - static { - eventStart = -1; - dataFetchStart = -1; - dataLogStart = -1; - eventMax = -1; - eventAvg = -1; - dataFetchMax = -1; - dataFetchAvg = -1; - dataLogMax = -1; - dataLogAvg = -1; - } - - private static long getMillis() { - return RobotController.getFPGATime()/1000; - } - - private static double calculateAvg(double original, long newData) { - if(original == -1) { - return newData; - } - return (original+newData)/2D; - } - - /** - * Resets the event log timer - */ - static void startEventLogCycle() { - eventStart = getMillis(); - } - - /** - * Takes the current value of the event log timer and uses it to update the max and avg cycle times - */ - static void endEventLogCycle() { - long elapsedTime = getMillis() - eventStart; - eventMax = Math.max(eventMax, elapsedTime); - eventAvg = calculateAvg(eventAvg, elapsedTime); - } - - /** - * Resets the data fetch timer - */ - static void startDataFetchCycle() { - dataFetchStart = getMillis(); - } - - /** - * Takes the current value of the data fetch timer and uses it to update the max and avg cycle times - */ - static void endDataFetchCycle() { - long elapsedTime = getMillis() - dataFetchStart; - dataFetchMax = Math.max(dataFetchMax, elapsedTime); - dataFetchAvg = calculateAvg(dataFetchAvg, elapsedTime); - } - - /** - * Resets the data log timer - */ - static void startDataLogCycle() { - dataLogStart = getMillis(); - } - - /** - * Takes the current value of the data log timer and uses it to update the max and avg cycle times - */ - static void endDataLogCycle() { - long elapsedTime = getMillis() - dataLogStart; - dataLogMax = Math.max(dataLogMax, elapsedTime); - dataLogAvg = calculateAvg(dataLogAvg, elapsedTime); - } - - /** - * @return The max time spent logging events - */ - public static double getMaxEventLogCycleTime() { - return eventMax; - } - - /** - * @return The average time spent logging events - */ - public static double getAvgEventLogCycleTime() { - return eventAvg; - } - - /** - * @return The max time spent fetching data - */ - public static double getMaxDataFetchCycleTime() { - return dataFetchMax; - } - - /** - * @return The average time spent fetching data - */ - public static double getAvgDataFetchCycleTime() { - return dataFetchAvg; - } - - /** - * @return The max time spent logging data - */ - public static double getMaxDataLogCycleTime() { - return dataLogMax; - } - - /** - * @return The average time spent logging data - */ - public static double getAvgDataLogCycleTime() { - return dataLogAvg; - } - - /** - * Sets up the data logging code to log the max and avg cycle times - * @throws IllegalStateException If the data logging code is already initialized or the required variable ids are already allocated - */ - public static void pushDataToCSV() throws IllegalStateException { - LogUtils.checkNotInit(); - ArrayList varIds = Log.getVarIds(); - if(varIds.contains("Max Event Log Cycle") || varIds.contains("Avg Event Log Cycle") || - varIds.contains("Max Data Fetch Cycle") || varIds.contains("Avg Data Fetch Cycle") || - varIds.contains("Max Data Log Cycle") || varIds.contains("Avg Data Log Cycle")) { - throw new IllegalStateException("Not all variable ids could be allocated"); - } - Log.registerDoubleVar("Max Event Log Cycle", TimeLog::getMaxEventLogCycleTime); - Log.registerDoubleVar("Avg Event Log Cycle", TimeLog::getAvgEventLogCycleTime); - Log.registerDoubleVar("Max Data Fetch Cycle", TimeLog::getMaxDataFetchCycleTime); - Log.registerDoubleVar("Avg Data Fetch Cycle", TimeLog::getAvgDataFetchCycleTime); - Log.registerDoubleVar("Max Data Log Cycle", TimeLog::getMaxDataLogCycleTime); - Log.registerDoubleVar("Avg Data Log Cycle", TimeLog::getAvgDataLogCycleTime); - } - - private TimeLog() {} - -} \ No newline at end of file