datadog-define-tags by AOP

Define yourself tags of datadog by AOP


1、POM增加


<!-- add datadog-agent lib for add request information to datadog.com -->
<dependency>
   <groupId>com.datadoghq</groupId>
   <artifactId>dd-java-agent</artifactId>
   <version>0.88.0</version>
</dependency>

2、启动添加注解:proxy by glibc or others method

package com.example.inv;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication(scanBasePackages = {"com.example.inv", "com.example.auditlog", "com.example.admin", "com.example.security", "com.example.core"},
  exclude = {SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class})
@EnableJpaAuditing
/*@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)*/
@EnableAsync
public class InvApplication extends SpringBootServletInitializer {

  public static void main(String[] args) {
    SpringApplication.run(InvApplication.class, args);
  }
}


3、开关AOP,配置文件中增加
 

#aop
spring.aop.proxy-target-class=true
spring.aop.auto=true

      proxy-target-class属性值决定是基于接口的还是基于类的代理被创建。如果proxy-target-class 属性值被设置为true,那么基于类的代理将起作用(这时需要cglib库)。

       如果proxy-target-class属值被设置为false或者这个属性被省略,那么标准的JDK 基于接口的代理将起作用。

4、定义AOP,注入datadogtags upload to datadog.com

 

package com.exmaple.inv.configuration;

import com.alibaba.fastjson.JSON;
import io.opentracing.Span;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

//datadog-agent
import io.opentracing.util.GlobalTracer;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

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

@Aspect
@Component
public class DatadogTagsAnnoAspectLogAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(DatadogTagsAnnoAspectLogAspect.class);

    @Pointcut("execution(public * com.michaels.inv.inventory.controller.*.*(..))")
    public void LogAspect(){}

    @Around("LogAspect()")
    public Object deAround(ProceedingJoinPoint joinPoint) throws Throwable{

        /*ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        //这里可以获取到get请求的参数和其他信息
        LOGGER.info("请求开始, 各个参数, url: {}, method: {}, uri: {}, params: {}", url, method, uri, queryString);
        //重点 这里就是获取@RequestBody参数的关键  调试的情况下 可以看到o变量已经获取到了请求的参数
        Object[] o = joinPoint.getArgs();
        LOGGER.info("o.toString():====>{}", o.toString());

        // Get the active span
        final Span span = GlobalTracer.get().activeSpan();
        if (span != null) {
            // customer_id -> 254889
            // customer_tier -> platinum
            // cart_value -> 867
            span.setTag("request.parameters", url+"|"+method+"|"+uri+"|"+queryString);

            System.out.println("********************>>>>LogAspect");
        }*/


        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
        Map map = request.getParameterMap();

        Enumeration<String> enumeration = request.getParameterNames();
        Map<String,String> parameterMap = new HashMap<String,String>();
        while (enumeration.hasMoreElements()){
            String parameter = enumeration.nextElement();
            parameterMap.put(parameter,request.getParameter(parameter));
        }
        String strRequest = JSON.toJSONString(parameterMap);

        final Span span = GlobalTracer.get().activeSpan();
        if (span != null) {
            // customer_id -> 254889
            // customer_tier -> platinum
            // cart_value -> 867
            span.setTag("michaels-request-info-deAround.REQUEST", strRequest);
            span.setTag("michaels-request-info-deAround.METHOD", request.getMethod().toString());
            span.setTag("michaels-request-info-deAround.URL", request.getRequestURL().toString());
            span.setTag("michaels-request-info-deAround.ClassName", joinPoint.getSignature().getDeclaringTypeName()  );
            span.setTag("michaels-request-info-deAround.MethodName", joinPoint.getSignature().getName()  );
            span.setTag("michaels-request-info-deAround.QueryString",  request.getQueryString().toString() );
            span.setTag("michaels-request-info-deAround.Header:content-type",  request.getHeader("content-type"));
            span.setTag("michaels-request-info-deAround.Header:host:user-agent",  request.getHeader("host"));
            span.setTag("michaels-request-info-deAround.Header",  request.getHeader("user-agent"));

            System.out.println(">>>>>>>>>>>>>>>>>> 【doAround】");
        }

        LOGGER.info( "【请求 REQUEST 参数】" + strRequest );


        ///System.out.println("doAround");
        return joinPoint.proceed();
    }

    @Before("LogAspect()")
    public void doBefore(JoinPoint joinPoint){

/*        //获取当前登录人信息
        //Subject subject = SecurityUtils.getSubject();
        //SysUser user = (SysUser)subject.getPrincipal();
        //获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        String requestInfo = request.toString();*/


/*
        方法一:
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //QueryString
        LOGGER.info("QueryString={}", request.getQueryString().toString());

        //request.getRequestURI()
        LOGGER.info("getRequestURI={}", request.getRequestURI().toString());

        //URL
        LOGGER.info("URL={}",request.getRequestURL());

        //Method
        LOGGER.info("Method={}",request.getMethod());

        //IP
        LOGGER.info("IP={}",request.getRemoteAddr());

        //Class.Method
        LOGGER.info("CLass.Method={}",joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName()+"()");

        //Args
        LOGGER.info("Args={}",joinPoint.getArgs());

        // Get the active span
        final Span span = GlobalTracer.get().activeSpan();
        if (span != null) {
            // customer_id -> 254889
            // customer_tier -> platinum
            // cart_value -> 867
           // span.setTag("request.getPathInfo", request.getPathInfo().toString());
           // span.setTag("request.info", request.getRequestURL().toString());

            System.out.println("********************====== doBefore");
        }*/

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
        Map map = request.getParameterMap();

        Enumeration<String> enumeration = request.getParameterNames();
        Map<String,String> parameterMap = new HashMap<String,String>();
        while (enumeration.hasMoreElements()){
            String parameter = enumeration.nextElement();
            parameterMap.put(parameter,request.getParameter(parameter));
        }
        String strRequest = JSON.toJSONString(parameterMap);

        final Span span = GlobalTracer.get().activeSpan();
        if (span != null) {
            // customer_id -> 254889
            // customer_tier -> platinum
            // cart_value -> 867
            span.setTag("michaels-request-info-doBefore.REQUEST", strRequest);
            span.setTag("michaels-request-info-doBefore.METHOD", request.getMethod().toString());
            span.setTag("michaels-request-info-doBefore.URL", request.getRequestURL().toString());
            span.setTag("michaels-request-info-doBefore.ClassName", joinPoint.getSignature().getDeclaringTypeName()  );
            span.setTag("michaels-request-info-doBefore.MethodName", joinPoint.getSignature().getName()  );
            span.setTag("michaels-request-info-doBefore.QueryString",  request.getQueryString().toString() );
            span.setTag("michaels-request-info-doBefore.Header:content-type",  request.getHeader("content-type"));
            span.setTag("michaels-request-info-doBefore.Header:host",  request.getHeader("host"));
            span.setTag("michaels-request-info-doBefore.Header:user-agent",  request.getHeader("user-agent"));

            System.out.println("********************====== 【doBefore】");
        }

        LOGGER.info( "【请求 REQUEST 参数】" + strRequest );

    }

    @After("LogAspect()")
    public void doAfter(JoinPoint joinPoint){
        System.out.println("doAfter");
    }

    @AfterReturning("LogAspect()")
    public void doAfterReturning(JoinPoint joinPoint){
        System.out.println("doAfterReturning");
    }

    @AfterThrowing("LogAspect()")
    public void deAfterThrowing(JoinPoint joinPoint){
        System.out.println("deAfterThrowing");
    }

}



5、自定义注解,选用修改代码,注入datadogtags upload to datadog.com

package com.exmaple.inv.configuration;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface DatadogTagsAnno {
    String param() default "";
}

package com.exmaple.inv.configuration;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.Date;


@Aspect
@Component
public class DatadogTagsAnnoAspect {

    @Around("@annotation(DatadogTagsAnno)")
    public Object around(ProceedingJoinPoint joinPoint, DatadogTagsAnno DatadogTagsAnno) throws Throwable {
        System.out.println("方法开始时间是:"+new Date());
        Object oResult = joinPoint.proceed();
        System.out.println("方法结束时间是:"+new Date()) ;
        return oResult;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值