log4j学习笔记(二)

二、通过配置文件输出日志

1.配置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="ConsoleAppender"
		class="org.apache.log4j.ConsoleAppender">
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%d [%c] %p - %m%n" />
		</layout>
	</appender>
	<!-- 输出到指定文件Log.txt -->
	<appender name="debug" class="org.apache.log4j.FileAppender">
		<param name="File" value="debug.txt" />
		<param name="Append" value="true" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%d [%c] %p - %m%n" />
		</layout>
	</appender>
	<!-- 每分钟产生一个日志文件 -->
	<appender name="daily" class="org.apache.log4j.DailyRollingFileAppender">
	 	<param name="threshold" value="debug" />
		<param name="File" value="daily.txt" />
		<param name="Append" value="true" />
		<param name="DatePattern" value="'.'yyyy-MM-dd-HH-mm"/>
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%d [%c] %p - %m%n" />
		</layout>
	</appender>
	<appender name="error" class="org.apache.log4j.FileAppender">
		<param name="File" value="error.txt" />
		<param name="Append" value="true" />
		<layout class="org.apache.log4j.PatternLayout">
			<param name="ConversionPattern" value="%d [%c] %p - %m%n" />
		</layout>
	</appender>
	<!-- 包pkg1定义的 日志输入方式,该包下的类创建的loger将会同时按debug,error, ConsoleAppender方式输出 -->
	<logger name="pkg1" additivity="false">
		<level value="debug" />
		<appender-ref ref="debug" />
		<appender-ref ref="error" />
		<appender-ref ref="daily" />
		<appender-ref ref="ConsoleAppender" />
	</logger>
	<!-- root 日志记录器,如果某个类所在的包没有定义日志输出,则日志记录器会查找上级包所定义的输出方式,
		如果向上一致没有找到,则按 root 中定义输出 -->
	<root>
		<priority value="debug" />
		<appender-ref ref="ConsoleAppender" />
	</root>
</log4j:configuration>


2.创建应用类log4jtest.LogTest_Config.java
package log4jtest;

import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

public class LogTest_Config {

	public static Logger log = Logger.getLogger(LogTest_Config.class);

	public static void main(String[] args) {
		DOMConfigurator.configure("conf/log4j.xml");

		log.debug("debug:");
		log.info("info:");
		log.warn("warn:");
		log.error("error:");
		log.fatal("fatal:");

	}
}


  创建应用类pkg1.AAA.java
package pkg1;

import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

public class AAA {

	public static Logger log = Logger.getLogger(AAA.class);

	public static void main(String[] args) {
		DOMConfigurator.configure("conf/log4j.xml");

		log.debug("debug:");
		log.info("info:");
		log.warn("warn:");
		log.error("error:");
		log.fatal("fatal:");

	}
}

你可能感兴趣的:(java,apache,log4j,xml)