Java - One liner to Configure Logging

Often while writing some quick test or doing a prototype, we want to use logging. But we do not want to spend any time writing a properties file and doing the whole setup.

However there is a quick way to get log4j ready to use in a single line.
Log4j provides a BasicConfigurator which can be used to quickly configure the logging.

Usage Example -

public class LoggingOneLiner1 {

 private static final Logger logger = Logger
   .getLogger(LoggingOneLiner1.class);

 public static void main(String[] args) {
  // Configure the logging - this does the whole setup
  BasicConfigurator.configure();

  // Optional Step - change the logging level to INFO from default DEBUG
  Logger.getRootLogger().setLevel(Level.INFO);

  logger.info("Its nice to to be able to configure logging in one line");
  logger.debug("I like quick and dirty java tricks");

 }

}

From the api docs of log4j -
  • The invocation of the BasicConfigurator.configure method creates a rather simple log4j setup. 
  • This method is hardwired to add to the root logger aConsoleAppender. The output will be formatted using a PatternLayout set to the pattern "%-4r [%t] %-5p %c %x - %m%n".
  • Note that by default, the root logger is assigned to Level.DEBUG.


Comments

Popular posts from this blog

Prefer ThreadLocalRandom over Random

Shortest Distance Graph Algorithms - How do they differ?