Good examples using java.util.logging
Here are some examples of how to use the java.util.logging
package to log messages in Java:
- Basic logging:
import java.util.logging.Logger;
public class Main {
private static final Logger LOGGER = Logger.getLogger(Main.class.getName());
public static void main(String[] args) {
LOGGER.info("Hello World");
}
}
This will log an "info" level message to the default logger.
- Logging with custom levels:
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
private static final Logger LOGGER = Logger.getLogger(Main.class.getName());
public static void main(String[] args) {
LOGGER.log(Level.SEVERE, "An error occurred");
LOGGER.log(Level.WARNING, "A warning message");
LOGGER.log(Level.INFO, "An informative message");
LOGGER.log(Level.CONFIG, "A configuration message");
LOGGER.log(Level.FINE, "A fine-grained trace message");
LOGGER.log(Level.FINER, "A finer-grained trace message");
LOGGER.log(Level.FINEST, "A finest-grained trace message");
}
}
This will log messages with different levels (SEVERE, WARNING, etc.) to the default logger.
- Logging with exception:
import java.io.IOException;
import java.util.logging.Logger;
public class Main {
private static final Logger LOGGER = Logger.getLogger(Main.class.getName());
public static void main(String[] args) {
try {
throw new IOException("An I/O exception occurred");
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "An error occurred", e);
}
}
}
This will