ITeye博客

log4j将包内的所有类日志指定文件输出

cloudeagle_bupt · 2016-11-06 22:51 · Markdown

package logTest;



import org.apache.commons.logging.Log;   
import org.apache.commons.logging.LogFactory; 

public class LogTest {

	 public static final Log LOG =
			    LogFactory.getLog(LogTest.class);
	 
	 public void test() {
		 LOG.info("test1") ;
		 LOG.debug("test1") ;
	 }
}
package logTest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class LogTest2 {
 public static final Log LOG =
  LogFactory.getLog(LogTest2.class);
 
 public static void main(String[] args) {
 LOG.info("test2") ;
 LOG.debug("test2") ;
 new LogTest().test() ;
}

}
log4j.properties配置:
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.


LOG_DIR=F://LogTest/
log4j.rootLogger=INFO,console


#Console
log4j.appender.console=org.apache.log4j.ConsoleAppender 
log4j.appender.console.Target=System.out 
log4j.appender.console.layout=org.apache.log4j.PatternLayout 
log4j.appender.console.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss} [%c-%L]-[%p] %m%n 


#test package print out
log4j.logger.logTest=INFO,logT 
log4j.appender.logT=org.apache.log4j.RollingFileAppender 
log4j.appender.logT.MaxFileSize=10240KB 
log4j.appender.logT.MaxBackupIndex=2 
log4j.appender.logT.File=${LOG_DIR}/test.log 
log4j.appender.logT.layout=org.apache.log4j.PatternLayout 
log4j.appender.logT.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss} [%c-%L]-[%p] %m%n

注意,这里一开始犯了一个错误,eclpise默认在src下面找log4j.properties文件,否则就提示:log4j:WARN No appenders could be found for logger

结果输出:

2016-11-06 22:45:30 [logTest.LogTest2-11]-[INFO] test2
2016-11-06 22:45:30 [logTest.LogTest-14]-[INFO] test1

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。