使用 log4j
首先定义 log4j.xml,它定义了控制台和文件 appender,如下所示:
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>
<appender name="CA" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-4r [%t] %-5p %c %x - %m%n" />
</layout>
</appender>
<appender name="Daily" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="logs/sample.log" />
<param name="DatePattern" value="'.'yyyy-MM-dd-HH-mm" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d [%t] - %m%n%n%n" />
</layout>
</appender>
<root>
<appender-ref ref="CA" />
<appender-ref ref="Daily" />
</root>
</log4j:configuration>
将此 xml 文件放在类路径中......同时将 log4j 保留在类路径中
示例代码是:
包 com.vanilla.helloworld;
导入 org.apache.log4j.*;
public class HelloWorld
{
static final Logger logger = Logger.getLogger(HelloWorld.class);
public static void main(String[] args) throws InterruptedException
{
logger.info("I am going to log to file as well as console");
}
}