企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
一、定义访问日志内容记录实体类 >创建accesslog包 ![](https://img.kancloud.cn/49/1e/491ef0858487c55a6dcc613884526984_372x144.png) ~~~ @Data public class AccessLog { //访问者用户名 private String username; //请求路径 private String url; //请求消耗时长 private Integer duration; //http 方法:GET、POST等 private String httpMethod; //http 请求响应状态码 private Integer httpStatus; //访问者ip private String ip; //此条记录的创建时间 private Date createTime; } ~~~ 二、获取ip访问地址的工具类 >放uitls下 ![](https://img.kancloud.cn/e1/d1/e1d18e8f0e9eaf825e2750a753500258_403x162.png) ~~~ public class AdrressIpUtils { /** * 获取Ip地址 * @param request HttpServletRequest * @return ip */ public static String getIpAdrress(HttpServletRequest request) { String Xip = request.getHeader("X-Real-IP"); String XFor = request.getHeader("X-Forwarded-For"); if(StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){ //多次反向代理后会有多个ip值,第一个ip才是真实ip int index = XFor.indexOf(","); if(index != -1){ return XFor.substring(0,index); }else{ return XFor; } } XFor = Xip; if(StringUtils.isNotEmpty(XFor) && !"unKnown".equalsIgnoreCase(XFor)){ return XFor; } if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) { XFor = request.getHeader("Proxy-Client-IP"); } if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) { XFor = request.getHeader("WL-Proxy-Client-IP"); } if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) { XFor = request.getHeader("HTTP_CLIENT_IP"); } if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) { XFor = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (StringUtils.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) { XFor = request.getRemoteAddr(); } return XFor; } } ~~~ 三、自定义日志拦截器 ![](https://img.kancloud.cn/1b/dc/1bdc914fea26b15b40ea765ceb27f5e9_460x257.png) ~~~ @Slf4j public class AccessLogInterceptor implements HandlerInterceptor { //请求开始时间标识 private static final String LOGGER_SEND_TIME = "SEND_TIME"; //请求日志实体标识 private static final String LOGGER_ACCESSLOG = "ACCESSLOG_ENTITY"; /** * 进入SpringMVC的Controller之前开始记录日志实体 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception { //创建日志实体 AccessLog accessLog = new AccessLog(); // 设置IP地址 accessLog.setIp(AdrressIpUtils.getIpAdrress(request)); //设置请求方法,GET,POST... accessLog.setHttpMethod(request.getMethod()); //设置请求路径 accessLog.setUrl(request.getRequestURI()); //设置请求开始时间 request.setAttribute(LOGGER_SEND_TIME,System.currentTimeMillis()); //设置请求实体到request内,方便afterCompletion方法调用 request.setAttribute(LOGGER_ACCESSLOG,accessLog); return true; } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception { //获取本次请求日志实体 AccessLog accessLog = (AccessLog) request.getAttribute(LOGGER_ACCESSLOG); //获取请求错误码,根据需求存入数据库,这里不保存 int status = response.getStatus(); accessLog.setHttpStatus(status); //设置访问者(这里暂时写死) // 因为不同的应用可能将访问者信息放在session里面,有的通过request传递, // 总之可以获取到,但获取的方法不同 accessLog.setUsername("admin"); //当前时间 long currentTime = System.currentTimeMillis(); //请求开始时间 long snedTime = Long.valueOf(request.getAttribute(LOGGER_SEND_TIME).toString()); //设置请求时间差 accessLog.setDuration(Integer.valueOf((currentTime - snedTime)+"")); accessLog.setCreateTime(new Date()); //将sysLog对象持久化保存 log.info(accessLog.toString()); } } ~~~ 四、拦截器注册 ~~~ @Configuration public class MyWebMvcConfigurer implements WebMvcConfigurer { //设置排除路径,spring boot 2.*,注意排除掉静态资源的路径,不然静态资源无法访问 private final String[] excludePath = {"/static"}; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new AccessLogInterceptor()).addPathPatterns("/**").excludePathPatterns(excludePath); } } ~~~ 拦截器已经注册过了,所以直接依次添加就好 ![](https://img.kancloud.cn/42/56/42560ffeaa0dc7cbd2793570cb106b12_1172x572.png) 五、增加日志输出 ![](https://img.kancloud.cn/da/97/da97d1fd81ebe13d5d4768f07d41c6ba_1105x735.png) ~~~ <RollingFile name="accessLog" fileName="./logs/boot-launch-accessLog.log" filePattern="./logs/boot-launch-accessLog-%d{yyyy-MM-dd}.log" append="true"> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS Z}\t%level\t%class\t%line\t%thread\t%msg%n"/> <Policies> <TimeBasedTriggeringPolicy/> </Policies> <!-- 此行以下为自动清理日志的配置 --> <DefaultRolloverStrategy> <Delete basePath="./logs"> <!-- glob 项为需要自动清理日志的pattern --> <IfFileName glob="*.log"/> <!-- 30d 表示自动清理掉30天以前的日志文件 --> <IfLastModified age="30d"/> </Delete> </DefaultRolloverStrategy> <!-- 此行以上为自动清理日志的配置 --> </RollingFile> ~~~ ~~~ <logger name="com.kimgao.bootlauch.config.accesslog.AccessLogInterceptor" level="info" additivity="false"> <AppenderRef ref="accessLog"/> </logger> ~~~ 启动服务,随便测试一个网址会发现控制台没有打印用户信息,log里面有打印用户信息。 ![](https://img.kancloud.cn/c3/9e/c39eab5fe71e958e961dbce1f69fcd3d_1828x753.png)