Java has a built in logging mechanism. This mechanism was adding to provide logging functionality to the base Java libraries. This removes external dependencies from your project, and allows you to use logging within the base framework.
Log4J has an incredible amount functionality, but requires that you add the framework to your project and its dependencies. There is also configuration required up front to use the logging.
The default logging mechanism is very easy to use. We simply create a
Logger
instance from the static class. Using it is as simple as calling
Logger.getAnonymousLogger();
. This allows you to create an anonymous logger which is a console logger. There is no default mechanism for logging to the file system. This accomplished by using a
FileHandler
.
A simple sample implementation is located below. I have please note the comments. The
NetBeans project is located here:
ExampleLogger.zip
ExampleLogger.java
package com.bluelotussoftware.example;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
@author <jyeary@bluelotussoftware.com>
@version
public class LoggerExample {
private static final Logger logger = Logger.getLogger(LoggerExample.class.getName());
private FileHandler fileHandler;
public LoggerExample() {
addFileHandler(logger);
}
@param
public static void main(String[] args) {
logger.info("main() method called.");
LoggerExample le = new LoggerExample();
try {
logger.info("Adding FileHandler");
logger.addHandler(new FileHandler(LoggerExample.class.getName()
+ ".main.log"));
logger.info("Added FileHandler to Logger");
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
logger.log(Level.SEVERE, null, ex);
}
logger.info("Logging for fun and profit");
logger.fine("Fine...");
logger.finer("Finer...");
logger.finest("Finest...");
logger.warning("Warning...");
logger.severe("Severe...");
logger.info("Logging complete.");
}
<code></code> <code></code>
@param <code></code> <code></code>
private void addFileHandler(Logger logger) {
try {
fileHandler = new FileHandler(LoggerExample.class.getName() + ".log");
} catch (IOException ex) {
logger.log(Level.SEVERE, null, ex);
} catch (SecurityException ex) {
logger.log(Level.SEVERE, null, ex);
}
logger.addHandler(fileHandler);
}
}
