In Java, java.util.logging
is a powerful and flexible logging utility for generating logs. Below are some good examples of how to use java.util.logging
for different purposes, such as logging messages, managing log levels, and configuring log handlers.
1. Basic Logging Example
This is a simple example to log messages at different levels using java.util.logging.Logger
.
import java.util.logging.*;
public class LoggingExample {
// Create a logger instance
private static final Logger logger = Logger.getLogger(LoggingExample.class.getName());
public static void main(String[] args) {
// Setting the logging level
logger.setLevel(Level.ALL);
// Log messages of various severity levels
logger.severe("This is a SEVERE message.");
logger.warning("This is a WARNING message.");
logger.info("This is an INFO message.");
logger.config("This is a CONFIG message.");
logger.fine("This is a FINE message.");
logger.finer("This is a FINER message.");
logger.finest("This is a FINEST message.");
}
}
Explanation:
Logger.getLogger()
is used to get a logger instance for the specified class.- Logging levels like
SEVERE
,WARNING
, andINFO
are used to print messages with different severity levels. - By default, the logging system logs messages at the
INFO
level and higher.
2. Logging with FileHandler
You can log messages to a file using FileHandler
.
import java.util.logging.*;
public class FileLoggingExample {
private static final Logger logger = Logger.getLogger(FileLoggingExample.class.getName());
public static void main(String[] args) throws Exception {
// Creating a FileHandler to log messages to a file
FileHandler fileHandler = new FileHandler("app.log", true);
logger.addHandler(fileHandler);
// Set the formatter to a simple format
SimpleFormatter formatter = new SimpleFormatter();
fileHandler.setFormatter(formatter);
// Log messages
logger.info("This is an INFO message that will be logged to a file.");
logger.warning("This is a WARNING message that will be logged to a file.");
}
}
Explanation:
- A
FileHandler
is created with a log file path (app.log
in this case). SimpleFormatter
formats the log entries in a simple way (you can also useXMLFormatter
).- The
true
flag in theFileHandler
constructor means the log file will be appended, not overwritten.
3. ConsoleHandler for Console Output
You can log messages to the console using ConsoleHandler
.
import java.util.logging.*;
public class ConsoleLoggingExample {
private static final Logger logger = Logger.getLogger(ConsoleLoggingExample.class.getName());
public static void main(String[] args) {
// Create a ConsoleHandler
ConsoleHandler consoleHandler = new ConsoleHandler();
logger.addHandler(consoleHandler);
// Set the logging level for the handler
consoleHandler.setLevel(Level.ALL);
// Log messages to the console
logger.info("This message is logged to the console.");
logger.severe("This is a SEVERE message on the console.");
}
}
Explanation:
- A
ConsoleHandler
is added to the logger, which will print log messages to the console. - You can control the logging level of the handler (
consoleHandler.setLevel(Level.ALL)
).
4. Custom Logging Formatter
You can create custom log formatters to control how logs are formatted.
import java.util.logging.*;
class CustomFormatter extends Formatter {
@Override
public String format(LogRecord record) {
return "[" + record.getLevel() + "] " + record.getMessage() + "\n";
}
}
public class CustomLoggingFormatterExample {
private static final Logger logger = Logger.getLogger(CustomLoggingFormatterExample.class.getName());
public static void main(String[] args) {
// Create a ConsoleHandler and apply the custom formatter
ConsoleHandler consoleHandler = new ConsoleHandler();
consoleHandler.setFormatter(new CustomFormatter());
logger.addHandler(consoleHandler);
// Log messages with custom format
logger.info("This message has a custom format.");
logger.severe("This is a SEVERE message with a custom format.");
}
}
Explanation:
- The
CustomFormatter
class overrides theformat
method to change the log format. - The log messages will now be printed with the specified custom format.
5. Setting Global Logging Properties via logging.properties
You can configure the logging behavior globally using a logging.properties
file.
logging.properties:
# Specify the log level for the root logger
.level = ALL
# Specify the handlers for logging output
handlers = java.util.logging.ConsoleHandler
# Set the console handler's log level
java.util.logging.ConsoleHandler.level = ALL
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
Java Code:
import java.util.logging.*;
public class LoggingPropertiesExample {
private static final Logger logger = Logger.getLogger(LoggingPropertiesExample.class.getName());
public static void main(String[] args) {
// Use the logging properties file for configuration
try {
LogManager.getLogManager().readConfiguration();
} catch (Exception e) {
e.printStackTrace();
}
// Log messages
logger.info("This message uses global logging properties.");
logger.warning("This is a WARNING message.");
}
}
Explanation:
- The
logging.properties
file is used to set up the logging configuration (e.g., level, handlers, formatters). - In the code,
LogManager.getLogManager().readConfiguration()
reads the configuration file.
6. Changing Log Levels Dynamically
You can change the logging level programmatically at runtime.
import java.util.logging.*;
public class DynamicLogLevelExample {
private static final Logger logger = Logger.getLogger(DynamicLogLevelExample.class.getName());
public static void main(String[] args) {
// Set the logging level dynamically
logger.setLevel(Level.WARNING);
// Log messages with different severity
logger.severe("This is a SEVERE message.");
logger.warning("This is a WARNING message.");
logger.info("This INFO message will not be logged due to the current log level.");
}
}
Explanation:
- The logging level can be set dynamically using
setLevel()
, filtering messages based on the configured level. - In this example, only messages at the
WARNING
level and above will be logged.
7. Using LogRecord
for Advanced Logging
You can create custom LogRecord
instances to log more detailed information.
import java.util.logging.*;
public class LogRecordExample {
private static final Logger logger = Logger.getLogger(LogRecordExample.class.getName());
public static void main(String[] args) {
// Create a custom LogRecord
LogRecord record = new LogRecord(Level.INFO, "Custom LogRecord message");
// Log the custom LogRecord
logger.log(record);
}
}
Explanation:
LogRecord
allows more fine-grained control over the log message, such as including custom data (e.g., user ID, session ID).- The
logger.log()
method is used to log theLogRecord
instance.
These examples demonstrate various ways to use java.util.logging
for logging messages, file output, custom formatting, and runtime configuration. You can configure logging to suit the specific needs of your application, from simple console logging to complex, file-based logging systems.