1.环境
下载log4j架包,配置到项目lib中
配置log4j.xml,拷贝到classpath下
2.java代码
static Logger log= Logger.getLogger("qqtt"); public void log(){ log.debug("Debug info."); log.info("Info info"); log.warn("Warn info"); log.error("Error info"); log.fatal("Fatal info"); } public static void main(String[] args) { // TODO Auto-generated method stub Log4jTest l=new Log4jTest(); l.log(); }
3.log4j.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'> <appender name="_rolling" class="org.apache.log4j.RollingFileAppender"> <param name="Threshold" value="ERROR" /> <param name="File" value="log4j_test.log" /> <param name="Append" value="true" /> <param name="MaxFileSize" value="3MB" /> <!--default is 10KB, format=xxKB,xxMB,xxGB--> <param name="MaxBackupIndex" value="3" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="[%d{yyyy-MM-dd HH:mm}] %-5p [%c]%n %m%n" /> </layout> </appender> <appender name="console" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d %-5p [%t] %C (%F:%L) - %m%n" /> </layout> </appender> <root> <priority value="info" /> <appender-ref ref="_rolling" /> <appender-ref ref="console" /> </root> </log4j:configuration>
4.说明
root中指定了输出的地方:_rolling:文件 console:屏幕
priority指定了输出消息的最低层:info
threshold是消息的过滤器
5.其他