Logging has been used in desktop and web-based applications for a long time. Logging is an integral part of every application and is used to collect data to investigate or detect issues in software. Developers often log the errors in their applications, typically saving them into a flat file or a database. This data can be used at a later point in time to provide insights into how your application has been performing, the errors that occur, their location, cause, and other related information.
This Java programming tutorial talks about the Java Logging API with relevant code examples to try out.
What is the Java Logging API?
Java introduced the Java Logging API to provide a uniform method for handling all platform logs. It exposes a service interface that libraries and applications can customize if needed. the JDK platform logs can take advantage of the same logging framework that the application uses, which can help reduce project dependencies.
Reading: Best Application Performance Monitoring Tools
Using the Java Logging API
You can leverage logging capabilities in Java by including the java.util.logging package in your programs. The following code snippet illustrates how you can create a logger in Java using the Java Logging API:
import java.util.logging.Logger; private final static logger LOGGER = Logger.getLogger(MyLoggerClass.class.getName());
Note that MyLoggerClass is the name of the class which should be present in a file having the same name with a .java extension – for example: MyLoggerClass.java.
What are Log Levels in Java?
Log levels are used to define the severity of a log message. You can take advantage of the Level class in the Java Logging API to define log levels. You can choose from the following list of log levels:
- SEVERE: Indicates a serious failure
- WARNING: Indicates a potential problem
- INFO: Used for informational messages
- CONFIG: Used for static configuration messages
- FINE: Provides tracing information
- FINER: A more detailed tracing message
- FINEST: An even more detailed tracing message
The following code snippet illustrates how you can set the log level in Java:
logger.setLevel(Level.INFO);
Note that once you have set a log level, log messages that have a level which is greater than or equal to the log level specified will be generated. As an example, since the log level has been set as Level.INFO here, your application will generate logs for INFO, WARNING and SEVERE log levels.
Reading: Logging Microservices: Challenges and Solutions
How to Create a Logger in Java
To create a logger instance in Java you can take advantage of the getLogger method, as shown in the following code example:
public class Author{ private static final Logger logger = Logger.getLogger(Author.class); public void displayAuthorDetails() { //Code shortened for brevity } }
If you want to create a custom logger implementation in Java, you should create a class that implements the System.Logger interface, which contains the following methods:
- getName()
- isLoggable()
- log()
Here is some example code:
public class MyCustomLogger implements System.Logger { @Override public String getName() { return “This is a custom logger.”; } @Override public boolean isLoggable(Level level) { return true; } @Override public void log(Level level, ResourceBundle bundle, String message, Throwable thrown) { //Write your own implementation here to log messages } @Override public void log(Level level, ResourceBundle bundle, String format, Object… params) { //Write your own implementation here to log formatted messages } }
What is a Logging Handler in Java?
A logger in the Java Logging API can have one or more handlers. When messages are logged using a logger, they are finally transmitted to the respective handlers unless they are excluded by a filter or the logger’s minimum log level. Note that you can even add multiple handlers to a logger instance.
A handler extracts the log messages from a logger, writes them to a terminal or file, sends them to a network logging service, transmits them to an operating system log, etc. You can deactivate a logging handler using setLevel(Level.OFF) or even reactivate it as needed.
The following code snippet shows how you can add a handler to a logger in Java:
logger.addHandler(new ConsoleHandler());
Here’s how the Handler abstract class is defined in the java.util.logging package:
public abstract class Handler extends Object
You can also create your own custom handler. The following code listing illustrates a custom logger in Java:
import java.util.logging.StreamHandler; import java.util.logging.LogRecord; public class MyCustomHandler extends StreamHandler { @Override public void publish(LogRecord logRecord) { //Wrie your own logic here to publish the log record super.publish(logRecord); } @Override public void flush() { super.flush(); } @Override public void close() throws SecurityException { super.close(); } }
Reading: Top Java IDEs and Code Editors
Understanding the Built-in Java Logging Handlers
Let’s now take a quick look at the built-in handlers and their purpose. There are several built-in handlers in Java such as the following:
- ConsoleHandler
- FileHandler
- MemoryHandler
- SocketHandler
- StreamHandler
We discuss each in detail below.
ConsoleHandler
As the name suggests, the ConsoleHandler is used to log messages to System.err. It leverages a SimpleFormatter by default. You can create an instance of ConsoleHandler as shown in the code snippet given below:
ConsoleHandler consoleHandler = new ConsoleHandler();
FileHandler
The FileHandler class is used to write messages to a file. You can use either a single file or a set of rotated files. When you use rotated files, new files will be created once the file size threshold is reached. You can use the following code snippet to create an instance of the FileHandler class using its default constructor in Java:
FileHandler fileHandler = new FileHandler();
You can also take advantage of the other overloaded constructors of this class to specify pattern or file size thresholds.
StreamHandler
The StreamHandler class in the Java Logging API is used to write messages to an output stream. The following code snippet illustrates the two constructors of this class:
StreamHandler streamHandler = new StreamHandler(); StreamHandler streamHandler = new StreamHandler(outputStream, formatter);
While the first constructor can be used to create an instance of the StreamHandler class without any output stream, the second one can be used to create an instance of this class with an output stream and a formatter. If you use the default constructor, you should use the setOutputStream() method to set an output stream for the handler.
SocketHandler
The SocketHandler class in the Java Logging API can be used to write messages to a particular network address using a socket. The following code snippet shows how you can create an instance of this class in Java:
SocketHandler socketHandler = new SocketHandler(host, port);
MemoryHandler
The MemoryHandler class can be used to store the messages in an internal buffer. Once this buffer is full, the old messages are overwritten by the newer ones. The following code snippet illustrates how you can create an instance of this class in Java:
MemoryHandler memoryHandler = MemoryHandler(); MemoryHandler memoryHandler = MemoryHandler(targetHandler, bufferSize, pushLevel);
What is a Java Logging Formatter?
A handler takes advantage of a formatter to format a message before the message is logged. There are some built-in formatters in Java Logging API. You can either use the built-in formatters or create one for your own. The following code snippet illustrates how you can use a custom formatter with a handler in Java.
ConsoleHandler consoleHandler = new ConsoleHandler(); consoleHandler.setFormatter(new MyFormatter()); Formatter formatter = consoleHandler.getFormatter();
Summary of Java Logging API
The Java Logging API makes it easy and seamless to work with logging in Java applications. In this article we discussed an overview of the Java Logging API and how to program it in Java. I’ll discuss more advanced logging operations using this API in a later post here.
read more Java programming and software development tutorials.