tomcat日志通过Log4j 2处理方案

Tomcat原生日志长期运行可能导致硬盘被耗尽,影响系统运行,本文讨论对Tomcat日志的绕接方案,使用log4j三方件的能力接管Tomcat日志能力从而实现绕接。

把需要jar包复制到tomcat lib

主要涉及下面三个包:

log4j-api-2.3.jar log4j-core-2.3.jar log4j-jul-2.3.jar

设置环境变量

编辑setenv.sh

#!/bin/sh
export  "CLASSPATH=$CLASSPATH:$CATALINA_HOME/lib/log4j-jul-2.3.jar:$CATALINA_HOME/lib/log4j-api-2.3.jar:$CATALINA_HOME/lib/log4j-core-2.3.jar"

export
 CATALINA_OPTS="$CATALINA_OPTS
 -Djava.util.logging.manager=org.apache.logging.log4j.jul.LogManager
 -Dlog4j.configurationFile=$CATALINA_HOME/conf/log4j2.xml"

编辑log4j2.xml



 
   ${sys:catalina.base}/logs   
   %d [%t] %-5p %c-%m%n 
  
    
        
        
      
        
          
          
          
        
      
        
          
          
          
        
      
        
          
          
          
     
    
  
 
         
        
      
   
     
   
    
     
   
 

修改server.xml


编写绕接类AccessLogValveExt

package com.xxx.tomcat.api.log;

import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.valves.AccessLogValve;

import java.io.CharArrayWriter;

public class AccessLogValveExt extends AccessLogValve
{
    */**
     * The descriptive information about
this implementation.
     */
    *protected static final String *info *=
            "com.huawei.cloudsop.tomcat.api.log.AccessLogValveExt/1.0";

    private static final org.apache.juli.logging.Log accessLog =
            org.apache.juli.logging.LogFactory.getLog(AccessLogValveExt.class);

    // rewrite log func of
    public void log(CharArrayWriter message) {
        accessLog.info(message.toString());
    }

    @Override
    public void log(Request request, Response response, long time) {
        super.log(request, response, time);
    }

    public String getInfo() {
        return info;
    }

    @Override
    protected synchronized void open() {
        // do nothing
    }
}

大功告成

你可能感兴趣的:(tomcat日志通过Log4j 2处理方案)