1、log4j.xml
<appender name="accessLogAppender" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="/opt/logs/data/stat/web/accessStat.log" />
<param name="DatePattern" value="'.'yyyy-MM-dd" />
<param name="Append" value="true" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%m%n" />
</layout>
</appender>
<logger name="accessLog" additivity="false">
<level value="INFO" />
<appender-ref ref="accessLogAppender" />
</logger>
2、applicationContext-servlet.xml
<!-- 登录拦截器 -->
<mvc:interceptors>
<bean class="com.youku.ddshow.controller.AccessLogInterceptor"/>
</mvc:interceptors>
3、com.youku.ddshow.controller.AccessLogInterceptor
package com.youku.ddshow.controller;
import java.net.URLEncoder;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.youku.ddshow.common.IPUtil;
import com.youku.ddshow.interceptor.CpsModel;
import com.youku.ddshow.interceptor.HostUser;
import com.youku.ddshow.interceptor.YktkModel;
import com.youku.ddshow.service.common.CpsInfo;
import com.youku.ddshow.user.cookie.CookieEntity;
/**
* 记录访问日志的拦截器
*
* @author [email protected]
* @since 2013-11-20 10:49
*/
public class AccessLogInterceptor extends HandlerInterceptorAdapter {
private Logger logger = LoggerFactory.getLogger(AccessLogInterceptor.class);
private Logger accesslogLogger = LoggerFactory.getLogger("accessLog");
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) {
try {
if (accesslogLogger.isInfoEnabled()) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
RequestContext requestContext = (RequestContext) request
.getAttribute(RequestContext.class.getName());
HostUser hostUser = requestContext == null ? null : requestContext.getHostUser();
int mid = 0;
int cid = 0;
int pid = 0;
int lpid = 0;
Object cpsModel = request.getAttribute("cpsModel");
if(cpsModel != null){
CpsInfo cps = ((CpsModel)cpsModel).getCpsInfo();
if (cps != null) {
mid = cps.getMid();
cid = cps.getCid();
pid = cps.getPid();
lpid = cps.getLpid();
}
}
int tId = 0;
int ytId = 0;
boolean isVip = false;
Object yktkModel = request.getAttribute("yktkModel");
if(yktkModel != null){
CookieEntity yktk = ((YktkModel)yktkModel).getCookieEntity();
if (yktk != null) {
tId = yktk.getTid();
ytId = yktk.getYtid();
isVip = yktk.isVip();
}
}
int userId = 0;
int machineId = 0;
int isTourist = 1;
if(hostUser != null) {
userId = hostUser.getUserId();
machineId = hostUser.getMid();
isTourist = hostUser.isTourist() ? 0 : 1;
}
String ip = IPUtil.getRealIP(httpServletRequest);
String method = httpServletRequest.getMethod();
String path = httpServletRequest.getServletPath();
String refer = httpServletRequest.getHeader("Referer");
String userAgent = httpServletRequest.getHeader("User-Agent");
ip = ip == null ? "" : ip;
method = method == null ? "" : method;
path = path == null ? "" : path;
refer = refer == null ? "" : refer;
userAgent = userAgent == null ? "" : userAgent.replaceAll("\t", "");
StringBuffer params = new StringBuffer();
for (Enumeration<?> em = httpServletRequest.getParameterNames(); em.hasMoreElements();) {
String name = em.nextElement().toString();
params.append(URLEncoder.encode(name, "UTF-8"))
.append("=")
.append(URLEncoder.encode(httpServletRequest.getParameter(name),
"UTF-8"));
if (em.hasMoreElements()) {
params.append("&");
}
}
accesslogLogger.info(new AccessLog(0, 0, 0, System.currentTimeMillis(),
ip, mid, cid, pid, lpid, String.valueOf(machineId), System.currentTimeMillis(),
"", ytId, userId, tId, isTourist, isVip, 0, method,
path, params.toString(), refer, userAgent, "", 0, 0).toLog());
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return true;
}
private class AccessLog {
private int version;
private int requestVersion;
private int domainId;
private long timestamp;
private String ip;
private int cpsMid;
private int cpsCid;
private int cpsPid;
private int cpsLpid;
private String machineId;
private long firstTimestamp;
private String sessionId;
private int ytId;
private int userId;
private int tId;
/**
* 0代表游客,1代表登录用户
*/
private int userType;
private boolean isVip;
private int pageId;
private String method;
private String path;
private String params;
private String refer;
private String userAgent;
private String ext;
private int step;
private int sessionStep;
public AccessLog(int version, int requestVersion, int domainId, long timestamp, String ip,
int cpsMid, int cpsCid, int cpsPid, int cpsLpid, String machineId,
long firstTimestamp, String sessionId, int tyId, int userId, int tId, int userType,
boolean vip, int pageId, String method, String path, String params, String refer,
String userAgent, String ext, int step, int sessionStep) {
this.version = version;
this.requestVersion = requestVersion;
this.domainId = domainId;
this.timestamp = timestamp;
this.ip = ip;
this.cpsMid = cpsMid;
this.cpsCid = cpsCid;
this.cpsPid = cpsPid;
this.cpsLpid = cpsLpid;
this.machineId = machineId;
this.firstTimestamp = firstTimestamp;
this.sessionId = sessionId;
this.ytId = tyId;
this.userId = userId;
this.tId = tId;
this.userType = userType;
isVip = vip;
this.pageId = pageId;
this.method = method;
this.path = path;
this.params = params;
this.refer = refer;
this.userAgent = userAgent;
this.ext = ext;
this.step = step;
this.sessionStep = sessionStep;
}
public String toLog() {
StringBuffer sb = new StringBuffer();
sb.append(version).append("\t").append(requestVersion).append("\t").append(domainId)
.append("\t").append(timestamp).append("\t").append(ip).append("\t")
.append(cpsMid).append("\t").append(cpsCid).append("\t").append(cpsPid)
.append("\t").append(cpsLpid).append("\t").append(machineId).append("\t")
.append(firstTimestamp).append("\t").append(sessionId).append("\t")
.append(ytId).append("\t").append(userId).append("\t").append(tId).append("\t")
.append(userType).append("\t").append(isVip ? "1" : "0").append("\t")
.append(pageId).append("\t").append(method).append("\t").append(path)
.append("\t").append(params).append("\t").append(refer).append("\t")
.append(userAgent).append("\t").append(ext).append("\t").append(step)
.append("\t").append(sessionStep);
return sb.toString();
}
}
}
4、package org.springframework.web.servlet.handler;
public abstract class HandlerInterceptorAdapter implements org.springframework.web.servlet.AsyncHandlerInterceptor {
public HandlerInterceptorAdapter() { /* compiled code */ }
public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, java.lang.Object handler) throws java.lang.Exception { /* compiled code */ }
public void postHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, java.lang.Object handler, org.springframework.web.servlet.ModelAndView modelAndView) throws java.lang.Exception { /* compiled code */ }
public void afterCompletion(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, java.lang.Object handler, java.lang.Exception ex) throws java.lang.Exception { /* compiled code */ }
public void afterConcurrentHandlingStarted(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, java.lang.Object handler) throws java.lang.Exception { /* compiled code */ }
6、Spring MVC 中 HandlerInterceptorAdapter的使用
对来自浏览器的请求的拦截,是利用Filter实现的,这种方式可以实现Bean预处理、后处理。
Spring MVC的拦截器不仅可实现Filter的所有功能,还可以更精确的控制拦截精度。
Spring为我们提供了org.springframework.web.servlet.handler.HandlerInterceptorAdapter这个适配器,继承此类,可以非常方便的实现自己的拦截器
参考
http://blog.csdn.net/liuwenbo0920/article/details/7283757
7、通过
private Logger accesslogLogger = LoggerFactory.getLogger("accessLog");
accesslogLogger.info(new AccessLog(0, 0, 0, System.currentTimeMillis(),
ip, mid, cid, pid, lpid, String.valueOf(machineId), System.currentTimeMillis(),
"", ytId, userId, tId, isTourist, isVip, 0, method,
path, params.toString(), refer, userAgent, "", 0, 0).toLog());