首页 > 其他分享 >使用AOP记录feign调用日志

使用AOP记录feign调用日志

时间:2024-03-20 17:29:42浏览次数:24  
标签:feign AOP value addDTO org import 日志 com public

文章目录

业务场景

记录请求第三方接口的情况。@DockLog可以用在类上也可以用在方法上

使用

DemoClientFeign


import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * DemoClientFeign
 *
 * @since 2024-03-12
 */
@DockLog
@FeignClient(url = "http://127.0.0.1:9707/demo_api", name = "demoClientFeign",
        fallbackFactory = DemlFeignFallBack.class)
public interface DemoClientFeign {

    /**
     * 获取token
     */
    @PostMapping(value = "/auth/login", produces = {MediaType.APPLICATION_JSON_VALUE})
    String getToken(@RequestBody String body);
}

DemlFeignFallBack


import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class DemlFeignFallBack implements FallbackFactory<DemoClientFeign> {

	@Override
    public DemlFeignFallBack create(Throwable throwable) {

        log.error("DemoClientFeign error", throwable);

        return new DemoClientFeign() {
            @Override
            public String getToken(String body) {
                return null;
            }
		}
	}
}

主要代码

DockLogAspect


import com.xxx.JacksonUtils;
import com.xxx.DockLogAddDTO;
import com.xxx.DockLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.lang.reflect.Method;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

/**
 * 三方feign请求-日志记录
 *
 * @since 2024/3/19 15:50
 */
@Aspect
@Component
@Slf4j
public class DockLogAspect {

    @Autowired
    private DockLogService dockLogService;
    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    private final ThreadLocal<DockLogAddDTO> tl = new ThreadLocal<>();

    @Pointcut("@within(com.ccreate.cnpc.openapi.annotations.DockLog) || @annotation(com.ccreate.cnpc.openapi.annotations.DockLog)")
    public void pointcut() {
    }

    @Before("pointcut()")
    public void before(JoinPoint joinPoint) {
        DockLogAddDTO addDTO = tl.get();
        if (addDTO == null) {
            addDTO = new DockLogAddDTO();
        }

        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        PostMapping postMapping = method.getAnnotation(PostMapping.class);
        GetMapping getMapping = method.getAnnotation(GetMapping.class);
        RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);

        if (postMapping == null && getMapping == null && requestMapping == null) {
            return;
        }

        String[] value = new String[]{};
        if (Objects.nonNull(postMapping)) {
            value = postMapping.value();
        }
        if (Objects.nonNull(getMapping)) {
            value = getMapping.value();
        }
        if (Objects.nonNull(requestMapping)) {
            value = requestMapping.value();
        }
        if (value.length == 0) {
            return;
        }

        Object[] args = joinPoint.getArgs();

        addDTO.setStartMillis(System.currentTimeMillis());
        addDTO.setRequest(JacksonUtils.toJson(args));
        addDTO.setUrl(joinUrl(value[0], methodSignature));

        tl.set(addDTO);
    }

    @AfterReturning(value = "pointcut()", returning = "obj")
    public void afterReturn(Object obj) {
        try {
            DockLogAddDTO addDTO = tl.get();
            if (Objects.isNull(addDTO)) {
                return;
            }

            // 异步保存
            CompletableFuture.runAsync(() -> {
                if (Objects.nonNull(obj)) {
                    addDTO.setSuccess(true);
                    addDTO.setResponse(JacksonUtils.toJson(obj));
                } else {
                    addDTO.setSuccess(false);
                }
                addDTO.setCompletedMillis(System.currentTimeMillis());
                // 保存
                dockLogService.add(addDTO);
            }, taskExecutor);
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            tl.remove();
        }
    }

    @AfterThrowing(pointcut = "pointcut()", throwing = "t")
    public void afterThrowing(JoinPoint jp, Throwable t) {
        try {
            DockLogAddDTO addDTO = tl.get();
            if (Objects.isNull(addDTO)) {
                return;
            }

            // 异步保存
            CompletableFuture.runAsync(() -> {
                addDTO.setSuccess(false);
                addDTO.setResponse(ExceptionUtils.getStackTrace(t));
                addDTO.setCompletedMillis(System.currentTimeMillis());
                // 保存
                dockLogService.add(addDTO);
            }, taskExecutor);
        } catch (Exception e) {
            log.error("afterThrowing exception", e);
        } finally {
            tl.remove();
        }
    }

    /**
     * 拼接URL
     */
    public String joinUrl(String url, Signature signature) {
        FeignClient feignClient = AnnotationUtils.findAnnotation(signature.getDeclaringType(), FeignClient.class);
        if (Objects.isNull(feignClient)) {
            return url;
        }

        return feignClient.url() + url;
    }
}

DockLog


import java.lang.annotation.*;

/**
 * 日志记录
 *
 * @since 2024/3/19 15:49
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DockLog {

}

DockLogService


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 三方接口feign请求日志 自定义服务实现类
 */
@Slf4j
@Service
public class DockLogService {

    /**
     * 新增三方接口feign请求日志
     *
     * @param params 三方接口feign请求日志信息
     * @author pengjin 2024-03-19
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(DockLogAddDTO params) {

        // 参数转成实体PO
        DockLogPO dockLogPo = CommonUtils.copyProperties(params, DockLogPO.class);

        Long startMillis = params.getStartMillis();
        Long completedMillis = params.getCompletedMillis();
        if (ObjectUtils.allNotNull(startMillis, completedMillis)) {
            dockLogPo.setTimeConsuming(completedMillis - startMillis);
        }

        return iDockLogService.save(dockLogPo);
    }
}

DockLogAddDTO


import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.io.Serializable;

/**
 * 三方接口feign请求日志
 */
@Data
@EqualsAndHashCode(callSuper = false)
@ApiModel(value = "三方接口feign请求日志新增参数对象", description = "三方接口feign请求日志")
public class DockLogAddDTO implements Serializable {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "id")
    private Long id;

    @ApiModelProperty(value = "请求")
    private String url;

    @ApiModelProperty(value = "请求参数")
    private String request;

    @ApiModelProperty(value = "返回参数")
    private String response;

    @ApiModelProperty(value = "是否成功:1-成功,0-未成功")
    private Boolean success;

    @ApiModelProperty(value = "请求耗时:毫秒")
    private Long timeConsuming;

    @ApiModelProperty(value = "请求开始时间")
    private Long startMillis;

    @ApiModelProperty(value = "请求结束时间")
    private Long completedMillis;
}

JacksonUtils


import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.json.JsonWriteFeature;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * JacksonUtils
 *
 * @author pengjin 2022/9/5
 * @see com.alibaba.nacos.common.utils.JacksonUtils
 */
@Slf4j
public final class JacksonUtils {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    static {
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        // 序列化配置,针对java8 时间
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));

        // 反序列化配置,针对java8 时间
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));

        MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
                .setSerializationInclusion(JsonInclude.Include.NON_NULL)
                .registerModules(javaTimeModule)
                .configure(JsonWriteFeature.QUOTE_FIELD_NAMES.mappedFeature(), true);
    }

    /**
     * Object to json string
     */
    public static String toJson(Object obj) {
        try {
            return MAPPER.writeValueAsString(obj);
        } catch (IOException e) {
            log.error("toJson error", e);
            throw E.of(BaseExceptionEnum.FORMAT_ERROR);
        }
    }

    /**
     * Json string deserialize to Jackson {@link JsonNode}.
     *
     * @param json json string
     * @return {@link JsonNode}
     */
    public static JsonNode toObj(String json) {
        try {
            return MAPPER.readTree(json);
        } catch (IOException e) {
            log.error("转JsonNode失败", e);
            throw E.of(BaseExceptionEnum.FORMAT_ERROR);
        }
    }

    /**
     * Json string deserialize to Object.
     *
     * @param json          json string
     * @param typeReference {@link TypeReference} of object
     * @param <T>           General type
     * @return object
     * @throws E if deserialize failed
     */
    public static <T> T toObj(String json, TypeReference<T> typeReference) {
        try {
            return MAPPER.readValue(json, typeReference);
        } catch (IOException e) {
            log.error("toObj error", e);
            throw E.of(BaseExceptionEnum.FORMAT_ERROR);
        }
    }

    /**
     * Json string deserialize to Object.
     *
     * @param json json string
     * @param type type of object
     * @param <T>  General type
     * @return object
     * @throws E if deserialize failed
     */
    public static <T> T toObj(String json, Class<T> type) {
        try {
            return MAPPER.readValue(json, type);
        } catch (IOException e) {
            log.error("toObj error", e);
            throw E.of(BaseExceptionEnum.FORMAT_ERROR);
        }
    }

    /**
     * Parse object to Jackson {@link JsonNode}.
     */
    public static JsonNode transferToJsonNode(Object obj) {
        return MAPPER.valueToTree(obj);
    }

    /**
     * Parse object to Jackson {@link ObjectNode}.
     */
    public static ObjectNode transferToObjectNode(Object obj) {
        return transferToJsonNode(obj).deepCopy();
    }

    /**
     * Parse object to Jackson {@link ObjectNode}.
     */
    public static ObjectNode transferToObjectNode(String json) {
        return toObj(json).deepCopy();
    }

    private JacksonUtils() {

    }
}

标签:feign,AOP,value,addDTO,org,import,日志,com,public
From: https://blog.csdn.net/Khazix/article/details/136882843

相关文章

  • 达梦归档归档日志丢失不连续的备份处理
    环境:OS:Centos7DB:DM8 1.归档目录看不出连续性[dmdba@host01arch]$ls-altotal148drwxr-xr-x2dmdbadinstall250Mar2014:09.drwxr-xr-x7dmdbadinstall67Mar1514:47..-rw-r--r--1dmdbadinstall118784Mar2014:03ARCHIVE_LOCAL1_0x61603......
  • 利用ssh隧道提升 feign 调用开发效率
    问题描述springcloud架构下,微服务间很多是通过feign进行调用的。作为一家小公司,很多微服务在开发环境没有部署实例,这就导致,想在本地做开发调试,要花精力起很多依赖服务。耗时费力。解决办法1、利用ssh隧道,让办公网可以访问测试环境(阿里云、默认不开放端口)的微服务。ssh-f......
  • CAD学习日志-003
    *******************************************************/ 保存默认自动保存间隔是10分钟(可改),自动创建备份副本。一般保存为2007的一个版本。向上兼容,便于交流。*******************************************************/ 加密20版本以上,可以保存为一个压缩包,然后对......
  • unity 设计一个日志系统需要注意什么
    在Unity中设计一个日志系统时,需要注意以下几点:日志级别:为了便于管理和过滤日志,可以为日志系统定义不同的日志级别,例如:Debug、Info、Warning、Error和Fatal。在输出日志时,可以根据当前设置的日志级别来决定是否输出该条日志。日志分类:为了便于查找和分析问题,可以为日志系统定......
  • 050_Windows下定时删除日志文件
    目录定时删除脚本计划任务定时执行定时删除脚本remauther:zhyqremdate:20220930rem******dellogStart******@echooff::删除三月前的日志forfiles/p"C:\powerShovel\api\logs"/m*.log-d-90/c"cmd/cdel/f@path"@echoonrem******dellogEnd******......
  • 小体量系统的日志收集
    最近客户有个新需求,就是想查看网站的访问情况。由于网站没有做google的统计和百度的统计,所以访问情况,只能通过日志查看,通过脚本的形式给客户导出也不太实际,给客户写个简单的页面,咱也做不到。 成熟的日志解决方案,那就是ELK,还有现在比较火的Loki,(当然还有很多其他解决方案,比如Splu......
  • Java-SpringAop 编程式事物实现
    SpringAop编程式事物实现1.数据库事物特性原子性多个数据库操作是不可分割的,只有所有的操作都执行成功,事物才能被提交;只要有一个操作执行失败,那么所有的操作都要回滚,数据库状态必须回复到操作之前的状态一致性事物操作成功后,数据库的状态和业务规则必须一致。例如:从A......
  • Spring-AOP面相切面编程示例(有详细注释)
    前提知识Spring-IOC容器注解方式使用https://blog.csdn.net/m0_61160520/article/details/136784799?spm=1001.2014.3001.5501切点表达式https://blog.csdn.net/m0_61160520/article/details/136782885?spm=1001.2014.3001.5501案例 1.创建项目2.导入依赖<dependenci......
  • 【APIM】Azure API Management Self-Host Gateway是否可以把请求的日志发送到Applicat
    问题描述AzureAPIManagementSelf-HostGateway是否可以把请求的日志发送到ApplicationInsights呢?让它和使用Azure上托管的Gateway一样呢?这是在APIM门户上配置API,设置的DiagnosticsLogs,当选择ApplicationInsights时,就可以把对接口请求时候所携带的Header/Body等信息发送......
  • nicelog--强大的Java日志组件,排查问题的利器
    ​ nicelog是一个功能强大的Java日志组件,它可以自动、手动收集日志,并通过traceId将日志关联起来,可极大提高排查问题的速度。官网:https://www.yuque.com/knifeblade/opensource/niceloggitee:https://gitee.com/knifeedge/niceloggithub:https://github.com/knife-blade/nicelog......