问题
I have a clean tomcat7 installation with log4j enabled (according to http://tomcat.apache.org/tomcat-7.0-doc/logging.html#Using_Log4j). "Application-level" logging do use log4j configuration (I direct logs to local syslog server). How can I make my application access.log to also use log4j? As far as I can see, I can choose among AccessLogValve, ExtendedAccessLogValve and JDBCAccessLogValve, but neighter of them enables me to log to syslog nor to use log4j.
回答1:
The log4j-scribe-appender project contains a Log4JAccessLogValve that will let you do just that.
回答2:
if you using Tomcat 7, you can extend the AccessLogValve by override this function:
/**
* Log the specified message to the log file, switching files if the date
* has changed since the previous log call.
*
* @param message Message to be logged
*/
public void log(String message) {
rotate();
/* In case something external rotated the file instead */
if (checkExists) {
synchronized (this) {
if (currentLogFile != null && !currentLogFile.exists()) {
try {
close(false);
} catch (Throwable e) {
ExceptionUtils.handleThrowable(e);
log.info(sm.getString("accessLogValve.closeFail"), e);
}
/* Make sure date is correct */
dateStamp = fileDateFormatter.format(
new Date(System.currentTimeMillis()));
open();
}
}
}
// Log this message
synchronized(this) {
if (writer != null) {
writer.println(message);
if (!buffered) {
writer.flush();
}
}
}
}
回答3:
This works for JDK-logging:
package org.apache.plugins;
import java.util.logging.Logger;
import org.apache.catalina.valves.AccessLogValve;
public class AccessLogJdkValve extends AccessLogValve {
private static Logger jdkLogger = Logger.getLogger(AccessLogJdkValve.class.getName());
@Override
public void log(String msg) {
jdkLogger.info(msg);
}
@Override
protected synchronized void open() {
// do nothing
}
}
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>tomcat7-conf</groupId>
<artifactId>tomcat7-conf</artifactId>
<version>1.0-RELEASE</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>common-tomcat-maven-plugin</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-catalina</artifactId>
<version>7.0.12</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
Just compile, make a jar, put a copy in /usr/share/tomcat7/lib/
, and modify server.xml
. I added it to my reference tomcat7 configuration on github.
来源:https://stackoverflow.com/questions/18056682/tomcat-access-logging-through-log4j