OperationLogger.java 3.95 KB
package com.bsth.oplog;

import com.bsth.annotation.BusinessDescription;
import com.bsth.entity.sys.OperationLog;
import com.bsth.entity.sys.SysUser;
import com.bsth.security.util.SecurityUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @author Hill
 */
@EnableScheduling
@Aspect
@Component
@ConditionalOnProperty("kafka.use")
public class OperationLogger {

    private final static Logger logger = LoggerFactory.getLogger(OperationLogger.class);

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private ObjectMapper mapper;

    private Queue<OperationLog> queue = new ConcurrentLinkedQueue<>();

    @After(value = "execution(public * com.bsth.service.impl.*.add*(..)) || execution(public * com.bsth.service.impl.*.modify*(..)) || execution(public * com.bsth.service.impl.*.remove*(..)) || execution(public * com.bsth.service.impl.*.batch*(..))")
    public void recordParams(JoinPoint point) {
        OperationLog operationLog = new OperationLog();
        DateTime dateTime = new DateTime();
        SysUser user = SecurityUtils.getCurrentUser();
        MethodSignature signature = (MethodSignature) point.getSignature();
        BusinessDescription description = signature.getMethod().getAnnotation(BusinessDescription.class);
        operationLog.setRq(dateTime.toString("yyyy-MM-dd"));
        operationLog.setOperateDate(dateTime.toDate());
        if (user != null) {
            operationLog.setOperateUser(user.getUserName());
        }
        if (description != null) {
            operationLog.setBusiness(description.value());
        }
        try {
            operationLog.setParams(mapper.writeValueAsString(point.getArgs()));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        queue.add(operationLog);
    }

    @Scheduled(cron = "0/10 * * * * ?")
    public void sendMessage() {
        String message = null;
        Map<String, Object> map = new HashMap<>();
        List<OperationLog> logs = new ArrayList<>();
        OperationLog log = null;
        map.put("type", "operate");
        map.put("data", logs);
        while ((log = queue.poll()) != null) {
            logs.add(log);
        }
        if (logs.size() < 1) {
            return;
        }
        try {
            message = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        if (message != null) {
            ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send("schedule-main-log", message);
            future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {

                @Override
                public void onSuccess(SendResult<String, String> result) {

                }

                @Override
                public void onFailure(Throwable ex) {
                    logger.error("kafka发送系统日志异常", ex);
                }
            });
        }
    }
}