Spring AOP拦截访问日志
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONObject;
import com.marks.zweb.common.context.AppContext;
@Aspect
@Component
public class AccessLogAspect {
private static final Logger log = LoggerFactory.getLogger("AccessLog");
// 切入点
@Around("execution( * com.marks.zweb.*.action.*.*(..) )")
public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
String uri = AppContext.getRequestURI();
log.info("request action start " + uri);
long start = System.currentTimeMillis();
// 调用被拦截的方法
Object object = pjp.proceed();
String json = JSONObject.toJSONString(object);
long time = System.currentTimeMillis() - start;
log.info("request action time=" + time + " uri:" + uri + " result: " + json);
return object;
}
}
<logger name="AccessLog" level="INFO"
additivity="false">
<appender-ref ref="CONSOLE" />
<appender-ref ref="AccessLog_FILE" />
</logger>
<!-- 访问日志文件输出 -->
<appender name="AccessLog_FILE"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>INFO</level>
</filter>
<encoder>
<pattern>%d{yyyy/MM/dd HH:mm:ss} [traceid=%X{traceid}] [uid=%X{uid}] [%thread] %-5level - %c{1}:%L %msg%n</pattern>
<charset>utf8</charset>
</encoder>
<file>./logs/app_AccessLog.log</file><!-- 文件存放路径 -->
<rollingPolicy
class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>./logs/app_AccessLog_%d{yyyy-MM-dd}.log</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
</appender>