1. 开启 log4j 框架内部的日志输出到控制台
# 在 log4j.properties 中添加
log4j.debug=true # 配置 log4j 框架内部的日志通过 System.out 输出
通过开启 log4j 内部日志,可以方便查看配置问题
n. 类作用
PropertyConfigurator : log4j.properties 对应的配置类
Q&A:
1. log4j.properties 配置了日志输出到控制台和文件,结果控制台的没有输出
log4j.rootLogger=STDOUT,INFO,ERROR
rootLogger 配置有问题,rootLogger 值对应的第一个串代表 rootLogger 的日志 level,应该改为:
log4j.rootLogger=INFO,STDOUT,INFO,ERROR
对应的源码:PropertyConfigurator#parseCategory(...)
1 void parseCategory(Properties props, Logger logger, String optionKey, String loggerName, String value) { 2 3 LogLog.debug("Parsing for [" + loggerName + "] with value=[" + value + "]."); 4 // We must skip over ',' but not white space 5 StringTokenizer st = new StringTokenizer(value, ","); 6 7 // If value is not in the form ", appender.." or "", then we should set 8 // the level of the loggeregory. 9 if (!(value.startsWith(",") || value.equals(""))) { 10 11 // just to be on the safe side... 12 if (!st.hasMoreTokens()) 13 return; 14 15 // rootLogger 配置的第一个串为 levelStr 16 String levelStr = st.nextToken(); 17 LogLog.debug("Level token is [" + levelStr + "]."); 18 19 // If the level value is inherited, set category level value to 20 // null. We also check that the user has not specified inherited for the 21 // root category. 22 if (INHERITED.equalsIgnoreCase(levelStr) || NULL.equalsIgnoreCase(levelStr)) { 23 if (loggerName.equals(INTERNAL_ROOT_NAME)) { 24 LogLog.warn("The root logger cannot be set to null."); 25 } else { 26 logger.setLevel(null); 27 } 28 } else { 29 logger.setLevel(OptionConverter.toLevel(levelStr, (Level) Level.DEBUG)); 30 } 31 LogLog.debug("Category " + loggerName + " set to " + logger.getLevel()); 32 } 33 34 // Begin by removing all existing appenders. 35 logger.removeAllAppenders(); 36 37 Appender appender; 38 String appenderName; 39 // rootLogger 配置的第二个串往后的串为 appenderName 40 while (st.hasMoreTokens()) { 41 appenderName = st.nextToken().trim(); 42 if (appenderName == null || appenderName.equals(",")) 43 continue; 44 LogLog.debug("Parsing appender named "" + appenderName + ""."); 45 appender = parseAppender(props, appenderName); 46 if (appender != null) { 47 logger.addAppender(appender); 48 } 49 } 50 }