springboot:使用mongo做日志存储

x33g5p2x  于2022-03-11 转载在 Spring  
字(4.2k)|赞(0)|评价(0)|浏览(330)

springboot:使用mongo做日志存储

导入依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

实体类

package com.hl.springbootmongodb.pojo;

import lombok.Data;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

//配置MongoDB的表名称
@Document(collection = "logs")
@Data
public class LogBean {
    private String id;
    private Integer userId;
    private String username;

    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date createDate;
    private String ip;
    private String className;//类名
    private String method;//方法名
    private String requestURI;//请求
    private String responseResults;//响应结果
}

工具类

package com.hl.springbootmongodb.util;

import javax.servlet.http.HttpServletRequest;

public class CommonUtils {
     /**
     * 默认IP地址
     */
   	 public final static String ERROR_IP = "127.0.0.1";
    
     public static String getUserIP(HttpServletRequest request) {
        // 优先取 X-Real-IP
        String ip = request.getHeader("X-Real-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-forwarded-for");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            if ("0:0:0:0:0:0:0:1".equals(ip)) {
                ip = ERROR_IP;
            }
        }
        if ("unknown".equalsIgnoreCase(ip)) {
            ip = ERROR_IP;
            return ip;
        }
        int index = ip.indexOf(',');
        if (index >= 0) {
            ip = ip.substring(0, index);
        }
        return ip;
    }
}

切面类

package com.hl.springbootmongodb.aspect;

import com.hl.springbootmongodb.pojo.LogBean;
import com.hl.springbootmongodb.util.CommonUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
@Aspect
public class MongoDbLogAspect {
    @Autowired
    private MongoTemplate mongoTemplate;

    //切点的注解  是指那些方法需要被执行"AOP"
    @Pointcut("execution(* com.hl.springbootmongodb.controller.*.*(..))")
    public void logPointCut(){

    }

    //返回后通知value="logPointCut()"是指通知是在logPointCut()切点返回后通知的
    //returning="rtv"是返回值
    //@AfterReturning这个注解是返回后通知的注解
    @AfterReturning(value="logPointCut()",returning="rtv")
    //JoinPoint是连接点的意思我们要获取到的如类名,方法名,请求参数等都是从连接点中取出来的
    public void afterLog(JoinPoint joinpoint, Object rtv) {
        System.out.println("进去切点。。。。。");
        LogBean logBean = new LogBean();
        //获取类名
        String classname = joinpoint.getTarget().getClass().getSimpleName();
        //获取方法名
        String method = joinpoint.getSignature().getName();
        //获取请求参数
        String requestParam = "";
        logBean.setClassName(classname);
        logBean.setMethod(method);
        logBean.setResponseResults(requestParam);
        logBean.setCreateDate(new Date());
        //返回值
        if (rtv != null) {
            logBean.setResponseResults(rtv.toString());
        }
        //获取request对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String requestURI = request.getRequestURI();
        logBean.setRequestURI(requestURI);
		/*	UserBean user = (UserBean) request.getSession().getAttribute("user");
		if(user!=null){
			logBean.setUserId(user.getId());
		}*/
        //获取ip地址是封装好的一个类
        String ip = CommonUtils.getUserIP(request);
        logBean.setIp(ip);
//        User user = (User) SecurityUtils.getSubject().getPrincipal();
//        logBean.setUsername(user.getName());
        //保存mongodb
        mongoTemplate.save(logBean);
        System.out.println("日志存储成功.........");
    }
}

controller层

@RestController
public class TestLog {

    @PostMapping("/hello")
    public String test(){
        return "ok";
    }
}

配置文件

spring.data.mongodb.uri=mongodb://testuser:password@127.0.0.1:27017/test

测试结果

相关文章