使用默认配置

默认配置为输出到控制台,且日志基本为ERROR.

  1. public void testUseDefaultConf() {
  2. Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
  3. logger.trace("trace level");
  4. logger.debug("debug level");
  5. logger.info("info level");
  6. logger.warn("warn level");
  7. logger.error("error level");
  8. logger.fatal("fatal level");
  9. }

其输出结果:

  1. 16:59:42.902 [main] ERROR - error level
  2. 16:59:42.906 [main] FATAL - fatal level

自定义配置文件位置

用Configurator执行初始化:

  1. public class LoadLog4jConf {
  2. public static void main(String[] args) throws IOException {
  3. InputStream resourceAsStream = Thread.currentThread().getContextClassLoader()
  4. .getResourceAsStream("log4j2/log4j2.xml");
  5. ConfigurationSource source = new ConfigurationSource(resourceAsStream);
  6. Configurator.initialize(null, source);
  7. Logger logger = LogManager.getLogger(LoadLog4jConf.class);
  8. logger.info("LoadLog4jConf");
  9. }
  10. }