要将log4j日志输出到控制台,可以使用以下方法:
log4j.rootLogger=DEBUG, Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
import org.apache.log4j.Logger;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.PatternLayout;
public class MyClass {
private static final Logger logger = Logger.getLogger(MyClass.class);
public static void main(String[] args) {
ConsoleAppender consoleAppender = new ConsoleAppender();
consoleAppender.setLayout(new PatternLayout("%-4r [%t] %-5p %c %x - %m%n"));
logger.addAppender(consoleAppender);
logger.debug("Debug message");
logger.info("Info message");
logger.warn("Warning message");
logger.error("Error message");
}
}
以上两种方法都可以将log4j日志输出到控制台。