Logging

Data Types and Exceptions in Java

Jim White

Java Developer

What is a log

  • Applications are made up of many lines of code
    • Apps contain a lot of control flow (if/then/else, for loops, while loops, etc.)
    • Apps contain a lot of classes and methods
    • Tracing through all the code can challenging
  • A log serves as an application diary
    • Documenting what code has been invoked
    • Documenting where problems/issue have occurred

A log is like a diary for the application - tracking events, good or bad, that have occurred in an application.

Data Types and Exceptions in Java

Logging

  • Java comes with built-in logging capability
  • We control what text goes to into the log
    • Similar to how we call on System.out.println() to leave messages in the console
  • Logging is used to record what's happened
    • This includes code executed, problems encountered, and resource (like a database) used
  • Logging assists developers monitor and understand application activity for debugging
  • Recorded log messages can be stored in a file, database, or other system
    • Allowing for historical review/comparison of log entries
Data Types and Exceptions in Java

Using Java logging

  • Import java.util.logging
  • Get a Logger object
    • Use getLogger(String) to get a Logger object
    • The String names the logger
    • Typically, name the logger with the class name
import java.util.logging.*;

class HelloWorld {

  public static Logger logger =
    Logger.getLogger("HelloWorld");

}
1 See https://docs.oracle.com/javase/8/docs/api/index.html?java/util/logging/Logger.html for additional log methods
Data Types and Exceptions in Java

Writting log messages

public static void main (String[] args) {
  logger.log(Level.INFO,
             "This is informational");
  logger.log(Level.SEVERE,
             "This is a critical message");
}
Nov 26, 2024 12:59:29 PM HelloWorld main
INFO: This is informational
Nov 26, 2024 12:59:29 PM HelloWorld main
SEVERE: This is a critical message
Data Types and Exceptions in Java

Log levels

Level Order
SEVERE highest importance
WARNING
INFO
CONFIG
FINE
FINER
FINEST lowest importance

Log levels indicated the importance of a log entry

1 Image courtesy https://unsplash.com/@vendavlog
Data Types and Exceptions in Java

Let's practice!

Data Types and Exceptions in Java

Preparing Video For Download...