import java.util.logging.*; public class MyLogger { private static final Logger LOGGER = Logger.getLogger(MyLogger.class.getName()); public void performSomeTask() { LOGGER.info("Task has started"); // perform some task LOGGER.info("Task has completed"); } }
import java.util.logging.*; public class MyLogger { private static final Logger LOGGER = Logger.getLogger(MyLogger.class.getName()); public void performSomeTask() { LOGGER.setLevel(Level.FINE); // set the log level LOGGER.info("Initializing task"); LOGGER.fine("Fetching data from database"); // perform some task LOGGER.fine("Sending data to remote server"); LOGGER.info("Task has completed"); } }
import java.util.logging.*; import java.io.File; import java.io.IOException; public class MyLogger { private static final Logger LOGGER = Logger.getLogger(MyLogger.class.getName()); public void performSomeTask() throws IOException { File logFile = new File("myapp.log"); if (!logFile.exists()) { logFile.createNewFile(); } FileHandler handler = new FileHandler(logFile.getAbsolutePath()); handler.setFormatter(new SimpleFormatter()); LOGGER.addHandler(handler); LOGGER.info("Task has started"); // perform some task LOGGER.info("Task has completed"); } }In this example, we log messages to a file instead of the console by adding a `FileHandler` to the logger instance. We also set a `SimpleFormatter` to format the log messages. All of these examples use the `java.util.logging` package, which is the standard library package that contains the Java Logger.