Log4j XML 配置方式

Log4j xml 配置文件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="console" class="org.apache.log4j.ConsoleAppender">  
        <layout class="org.apache.log4j.PatternLayout">  
            <param name="ConversionPattern"     
                value="Time: [%d{yyyy-MM-dd HH:mm:ss,SSS}] [%t] %p - %m%n" />  
        </layout>  
    </appender> 
	
	<appender name="appender" class="org.apache.log4j.FileAppender">
		<param name="File" value="appender.log" />
		<param name="Append" value="true" />
		<layout class="org.apache.log4j.PatternLayout">
		  <param name="ConversionPattern" value="Time: [%d{yyyy-MM-dd HH:mm:ss,SSS}] [%t] %p - %m%n" />
		</layout>
	</appender>
	
	<appender name="dailyAppender" class="org.apache.log4j.DailyRollingFileAppender">  
        <param name="File" value="daily.log" />    
        <param name="DatePattern" value="'.'yyyy-MM-dd'.log'" />    
        <layout class="org.apache.log4j.PatternLayout">  
         <param name="ConversionPattern"    
            value="Time: [%d{yyyy-MM-dd HH:mm:ss,SSS}] [%t] %p - %m%n" />  
        </layout>    
    </appender>  

	<logger name="MyAppender" additivity="false">  
        <level value="info"></level>
        <appender-ref ref="appender" />    
    </logger> 
    
    <logger name="MyConsole" additivity="false">  
        <level value="info"></level>
        <appender-ref ref="console" />    
    </logger>
    
    <logger name="MyDailyAppender" additivity="false">  
        <level value="info"></level>
        <appender-ref ref="dailyAppender" />    
    </logger> 

	<root>
		<level value="info" />
	</root>
</log4j:configuration>


java代码读取配置文件:
import org.apache.log4j.Logger;

public class LoggerManager {
	
	private Logger logger = null;
	
	public void setUpLogger(String loggerName) {
		logger = Logger.getLogger(loggerName);
	}
	
	public void debug(String message) {
		logger.debug(message);
	}
	
	public void info(String message) {
		logger.info(message);
	}
	
	public void error(String message, Exception e) {
		logger.error(message, e);
	}
	
	public void warning(String message) {
		logger.warn(message);
	}
	
	public static void main(String[] args) {
		LoggerManager logger = new LoggerManager();
		logger.setUpLogger("MyAppender");
		logger.info("This is a info message!");
		logger.error("This is error message", new ArrayIndexOutOfBoundsException());
		logger.debug("This is debug message");
	}
}



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