# Writing Log Entries

Using one LogService for error logs and another for application logs, each writing to its own directory.

Journeyman · Java · Updated November 16, 2026

By Gregor Dzierzon

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.

```java
LogService errorLogger = new LogService("errors");

// this will log to "errors/20240916.log"
errorLogger.logMessage("This is a test error message");
```

```java
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, a `List<String>`.
- `appLog`: the application log, a `List<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 `text` is a number: add `"Read GPA: "`, then the text, to `appLog`, and return the number.
- When `Double.parseDouble` throws: add `"Could not read GPA: "`, then the text, to `errorLog`, and return `0.0`.
- Each call adds exactly one entry, to one log.

Practiced live on the lesson page: write the Java right there and check it.

## Cheat sheets

- [The LogService](https://www.ask-codey.com/cheat-sheets/logging-exceptions-creating-the-logservice-cheat-sheet)

Source: https://www.ask-codey.com/lessons/logging-exceptions-writing-log-entries
