import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
类MyClass {
private Logger log = Logger.getLogger(MyClass.class);
public void writeInConsol(){
BasicConfigurator.configure(); log.info("I write in consol!");
}
public static void main(String [] args){
MyClass myClass = new MyClass(); myClass.writeInConsol();
}
}
答案 0 :(得分:0)
如果找不到配置文件,将使用DefaultConfiguration。这将导致日志记录输出进入控制台。
所以你需要log4j配置和FileAppender。请参阅此处的文档 http://logging.apache.org/log4j/2.x/manual/appenders.html
它将是这样的
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="MyApp" packages="">
<Appenders>
<File name="MyFile" fileName="logs/app.log">
<PatternLayout>
<Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
</PatternLayout>
</File>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="MyFile"/>
</Root>
</Loggers>
</Configuration>