要將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日志輸出到控制臺。