In this tutorial, we will find out about Java Logging and its different segments with the help of examples.
Java allows us to make and catch log messages and files through the process of logging.
In Java, logging requires structures and APIs. Java has a built-in logging structure in the java.util.logging package.
We can likewise use third-party systems like Log4j, Logback and a lot more for logging purposes.
Java Logging Components
The figure below represents the core components and the flow of control of the Java Logging API (java.util.logging).
The Logger class gives strategies to logging. We can launch objects from the Logger class and call its techniques for logging purposes.
Let’s take an example.
Logger logger = Logger.getLogger("newLoggerName");
The getLogger() method of the Logger class is used to find or create a new Logger. The string argument defines the name of the logger.
Here, this creates a new Logger object or returns an existing Logger with the same name.
It is a convention to define a Logger after the current class using class.getName().
Logger logger = Logger.getLogger(MyClass.class.getName());
Note: This method will throw NullPointerException if the passed name is null.
Each Logger has a level that determines the importance of the log message. There are 7 basic log levels:
|Log Level (in descending order)||Use|
|WARNING||warning message, a potential problem|
|INFO||general runtime information|
|FINE||general developer information (tracing messages)|
|FINER||detailed developer information (tracing messages)|
|FINEST||highly detailed developer information(tracing messages)|
|OFF||turn off logging for all levels (capture nothing)|
|ALL||turn on logging for all levels (capture everything)|
Each log level has an integer value that determines their severity except for two special log levels OFF and ALL.
Logging the message
By default, the best three log levels are constantly logged. To set an alternate level, we can use the accompanying code:
logger.setLevel(Level.LogLevel); // example logger.setLevel(Level.FINE);
In this example, only level FINE and levels above it are set to be logged. All other log messages are dropped.
Now to log a message, we use the log() method.
logger.log(Level.LogLevel, "log message"); // example logger.log(Level.INFO, "This is INFO log level message");
There are shorthand methods for logging at desired levels.
logger.info( "This is INFO log level message"); logger.warning( "This is WARNING log level message");
All log requests that have passed the set log level are then forwarded to the LogRecord.
Note: If a logger’s level is set to null, its level is inherited from its parent and so on up the tree.
A filter (if it is present) decides if the LogRecord ought to be sent or not. As the name recommends, it filters the log messages as per explicit standards.
A LogRecord is just passed from the logger to the log overseer and from the log controller to outer frameworks in the event that it passes the predefined measures.
// set a filter logger.setFilter(filter); // get a filter Filter filter = logger.getFilter();
The log handler or the appenders receive the LogRecord and exports it to various targets.
Java SE provides 5 built-in handlers:
|StreamHandler||writes to an OutputStream|
|ConsoleHandler||writes to console|
|FileHandler||writes to file|
|SocketHandler||writes to remote TCP ports|
|MemoryHandler||writes to memory|
A handler can pass the LogRecord to a filter to again determine whether it can be forwarded to external systems or not.
To add a new handler, we use the following code:
logger.addHandler(handler); // example Handler handler = new ConsoleHandler(); logger.addHandler(handler);
To remove a handler, we use the following code:
logger.removeHandler(handler); // example Handler handler = new ConsoleHandler(); logger.addHandler(handler); logger.removeHandler(handler);
A logger can have multiple handlers. To get all the handlers, we use the following code:
Handler handlers = logger.getHandlers();
An overseer can likewise use a Formatter to organize the LogRecord object into a string before sending out it to outside systems.
Java SE has two built-in Formatters:
|SimpleFormatter||formats LogRecord to string|
|XMLFormatter||formats LogRecord to XML form|
We can use the following code to format a handler:
// formats to string form handler.setFormatter(new SimpleFormatter()); // formats to XML form handler.setFormatter(new XMLFormatter());
The LogManager object monitors the worldwide logging data. It peruses and keeps up the logging setup and the logger instances.
The log manager is a singleton, which implies that just one instance of it is started up.
To acquire the log manager case, we use the accompanying code:
LogManager manager = new LogManager();
Advantages of Logging
Here are some of the advantages of logging in Java.
- helps in monitoring the flow of the program
- helps in capturing any errors that may occur
- provides support for problem diagnosis and debugging
Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.