Writing Log Entries
Using one LogService for error logs and another for application logs, each writing to its own directory.
Journeyman · Java · Updated
Once the LogService is defined you can create new log entries by creating a new instance of the service. You can determine if it will be an errors or application logger by the name that is passed into the constructor.
LogService errorLogger = new LogService("errors");
// this will log to "errors/20240916.log"
errorLogger.logMessage("This is a test error message");
LogService appLogger = new LogService("application");
// this will log to "application/20240916.log"
appLogger.logMessage("This is a test application message");
Do it: log a bad GPA and carry on
The grade book reads each student's GPA from text, and Double.parseDouble("n/a") throws a NumberFormatException. One bad GPA shouldn't stop the app. Catch it, write it in the error log, and carry on. A GPA that reads fine goes in the application log instead, so there's a record of it too.
The box has no files, so each log is a List<String>, and each entry is one string added to it. (A real LogService would add the date and time; leave them out here.)
The method gets three values:
text: the GPA as it was read from the file, such as"3.91"or"n/a".errorLog: the error log, aList<String>.appLog: the application log, aList<String>.
For example:
text |
Double.parseDouble(text) |
Added to | The entry | Returns |
|---|---|---|---|---|
"3.91" |
gives 3.91 |
appLog |
"Read GPA: 3.91" |
3.91 |
"n/a" |
throws a NumberFormatException |
errorLog |
"Could not read GPA: n/a" |
0.0 |
So loadGpa("n/a", errorLog, appLog) returns 0.0, and errorLog then holds "Could not read GPA: n/a".
Your job: change the method loadGpa(String text, List<String> errorLog, List<String> appLog) so it never crashes, and returns a double.
- When
textis a number: add"Read GPA: ", then the text, toappLog, and return the number. - When
Double.parseDoublethrows: add"Could not read GPA: ", then the text, toerrorLog, and return0.0. - Each call adds exactly one entry, to one log.
Practiced live on the lesson page: write the Java right there and check it.