Logging in Java
An Introduction |
Prof. David Bernstein |
Computer Science Department |
bernstdh@jmu.edu |
java.util.logging
Logger
:
LogRecord
:
Handler
:
LogRecord
objects to a variety of
destinations including memory, output streams, consoles,
files, and socketsFilter
:
Formatter
:
LogRecord
objectsLogger
object.
Logger
creates a LogRecord
.
Logger
(perhaps after checking a log level and/or
Filter
) passes the LogRecord
to
a Handler
.
Handler
uses a Formatter
is used to
format the LogRecord
.
severe(String message)
warning(String message)
fine(String message)
finest(String message)
log(Level level, String message
entering()
exiting()
throwing()
ConsoleHandler
FileHandler
SocketHandler
SimpleFormatter
XMLFormatter
import java.io.*; import java.util.logging.*; /** * An example that demonstrates how to use some of the * basic features of the java.util.logging package * * @author Prof. David Bernstein, James Madison University * @version 1.0 */ public class Driver { /** * The entry point * * @Param args The command line arguments (ignored) */ public static void main(String[] args) throws Exception { FileHandler handler; int result; Logger logger; // Get the default logger (alternatively, could create // one for this application) logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); // Create a FileHandler handler = new FileHandler("mylog.txt"); // Send logger output to our FileHandler logger.addHandler(handler); // Set the formatter handler.setFormatter(new SimpleFormatter()); // Request that everything above this level gets logged. logger.setLevel(Level.FINE); // Log a simple INFO message. logger.log(Level.FINE, "Starting"); try { result = 1 / 0; } catch (ArithmeticException ae) { logger.log(Level.WARNING, "Trouble dividing", ae); } logger.log(Level.FINER, "Finished"); } }