How can we make the logs print to the console?

In Java, you can print logs to the console using the following code:

  1. the logging utility in Java
import java.util.logging.*;

public class Main {
    private static final Logger logger = Logger.getLogger(Main.class.getName());

    public static void main(String[] args) {
        ConsoleHandler consoleHandler = new ConsoleHandler();
        consoleHandler.setLevel(Level.ALL);
        logger.addHandler(consoleHandler);

        logger.info("This is an info message");
        logger.warning("This is a warning message");
        logger.severe("This is a severe message");
    }
}

In the code above, we create a Logger object and associate it with a ConsoleHandler. We can then use the methods logger.info(), logger.warning(), and logger.severe() to print messages of different levels.

  1. The org.slf4j library.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Main {
    private static final Logger logger = LoggerFactory.getLogger(Main.class);

    public static void main(String[] args) {
        logger.info("This is an info message");
        logger.warn("This is a warning message");
        logger.error("This is an error message");
    }
}

In the above code, we use the LoggerFactory.getLogger() method to obtain a Logger object, and use the logger.info(), logger.warn(), and logger.error() methods to print log messages of different levels. It is important to make sure that the logback.xml file is properly configured at this point.

In both cases mentioned above, the method for logging to the console is to configure the ConsoleHandler (for the java.util.logging package) or the logback.xml file (for the org.slf4j package) to output to the console.

bannerAds