Logging Exceptions: an overview

Why applications usually write logs to text files rather than a database, before we build a simple logger.

Journeyman · Java · Updated

By

When exceptions happen, it is common to log their details. It is typically preferred to store logs in a text file rather than in a database for several reasons.

  • Performance: writing to log files is faster than writing to a database
  • Simplicity: text files are easy to set up and have no external dependencies to a database
  • Persistence: text files are not dependent on external services.
  • Ease of Access: text files can easily be viewed and shared, other users do not need custom software, but can open the log in Notepad
  • System Criticality: Log files should not be a bottleneck and should continue to work even if other systems fail
  • Log Rotation: new log files should automatically be created after a certain time or if the file gets too big
  • Human Readability: text logs are human readable, which makes them easy to debug
  • Infrastructure Cost: Text files do not require a database infrastructure.
  • Size and Volume: Log files can become extremely large. Text files are a more practical way to store high-volume logs, because each log entry is appended at the end of the file with no overhead for indexing

There are several well-known Java logging frameworks, such as Log4j. We will write a simple custom logger that can be used to log errors or other application events.

Do it: find what happened on one day

A teacher says "the grade book broke on Monday, September 16." The log is a text file with a line for every event, each one starting with its date, so finding that day's entries is a matter of keeping the lines that start with that date. Being able to do that quickly is one of the reasons logs are plain text.

The method gets two values:

  • log: the log's lines, a List<String>. Each line starts with its date in the form 2024-09-16, then the time, then the message.
  • date: the day to look for, in the same form, such as "2024-09-16".

For example:

List<String> log = List.of(
    "2024-09-15 17:02:11 Finished",
    "2024-09-16 09:15:02 Started",
    "2024-09-16 09:16:41 Could not find the file: honor_roll.csv",
    "2024-09-17 08:00:00 Started");
Line starts with Keep for "2024-09-16"?
2024-09-15 No
2024-09-16 Yes
2024-09-16 Yes
2024-09-17 No

So entriesOn(log, "2024-09-16") returns the 2 lines from September 16: "2024-09-16 09:15:02 Started", then the Could not find the file line.

Your job: write the method entriesOn(List<String> log, String date) so it returns a List<String>: the log's lines from that day.

  • Keep the lines that start with date.
  • Keep them in the log's order.
  • When no line is from that day, return an empty list.

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

Cheat sheets