Tomcat工程中的log4j配置

Tomcat工程中的log4j配置

1)log4j.properties文件内容如下,此文件要配置到ClassPath中去。
log4j.rootLogger=debug, stdout, R

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%d %5p [%t] (%F:%L) - %m%n

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=AccountBook.log

log4j.appender.R.MaxFileSize=1000KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1

log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d %5p [%t] (%F:%L) - %m%n

2)书写一个初始化Log4j的servlet如下:
public   class  Log4jInit  extends  HttpServlet {
    
private   static   final   long  serialVersionUID  =   - 4499302208753939187L ;
    
static  Logger logger  =  Logger.getLogger(Log4jInit. class );

     
public   void  init(ServletConfig config)  throws  ServletException {
         String prefix 
=  config.getServletContext().getRealPath( " / " );
         String file 
=  config.getInitParameter( " log4j " );
         String filePath 
=  prefix  +  file;
         Properties props 
=   new  Properties();
         
         
try  {
             FileInputStream istream 
=   new  FileInputStream(filePath);
             props.load(istream);
             istream.close();

             String logFile 
=  prefix  +  props.getProperty( " log4j.appender.R.File " ); // 设置路径
             props.setProperty( " log4j.appender.R.File " ,logFile);
             
             
//  装入log4j配置信息
             PropertyConfigurator.configure(props);
         } 
catch  (IOException e) {
             System.out.println(
" Could not read configuration file [ "   +  filePath  +   " ]. " );
             System.out.println(
" Ignoring configuration file [ "   +  filePath  +   " ]. " );
             
return ;
         }
     }
}

3)在Web.xml中配置Log4jInit如下:
     < servlet >
         
< servlet-name > log4j-init </ servlet-name >
         
< servlet-class >
             com.sitinspring.action.Log4jInit
         
</ servlet-class >
         
< init-param >
           
< param-name > log4j </ param-name >
           
< param-value > WEB-INF/classes/log4j.properties </ param-value >
         
</ init-param >
         
< load-on-startup > 1 </ load-on-startup >
    
</ servlet >

此后配置文件就出现在工程目录下。

你可能感兴趣的:(Tomcat工程中的log4j配置)