使用spring Aop统一日志管理----统计所有服务请求

一、使用切面来管理日志

      单个服务可以定义一个切面,在切点里把所有的controller给包起来,所有的controller均放在web包下:

package com.hand.hcf.app.expense.logaop;

import jline.internal.Log;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.LoggerFactory;
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.Arrays;
import java.util.logging.Logger;


/**
 * WebLogAspect
 *
 * @Auther: zhengbing.zhang
 * @Date:2020/6/28
 * @remark
 */


@Aspect
@Component
public class WebLogAspect {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(WebLogAspect.class);
    @Pointcut("execution(public	* com.hand.hcf.app.expense.*.web..*.*(..))")
    public	void webLog(){}

    @Before("webLog()")
    public	void	doBefore(JoinPoint joinPoint)	throws	Throwable	{
        //	接收到请求,记录请求内容
        ServletRequestAttributes attributes	=	(ServletRequestAttributes)	RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=attributes.getRequest();
        logger.info("URL:"+request.getRequestURL().toString());
        logger.info("HTTP_METHOD:"+request.getMethod());
        logger.info("IP	:"+	request.getRemoteAddr());
        logger.info("CLASS_METHOD:"	+joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
        logger.info("ARGS:"+Arrays.toString(joinPoint.getArgs()));
    }
    @AfterReturning(returning="ret",pointcut="webLog()")
    public	void	doAfterReturning(Object	ret)	throws	Throwable	{
        //	处理完请求,返回内容
        logger.info("RESPONSE	:	"	+	ret);
    }
}


可以通过此方式来记录请求的相关信息,url,method,ip,类和方法名以及方法的参数。

打印出的日志信息如下:

2020-06-28 10:38:22.194  INFO [fec-expense,,,] 35428 --- [  XNIO-1 task-1] c.h.hcf.app.expense.logaop.WebLogAspect  : URL:http://10.72.9.128:9096/api/expense/report/line/query/by/headerId
2020-06-28 10:38:22.195  INFO [fec-expense,,,] 35428 --- [  XNIO-1 task-1] c.h.hcf.app.expense.logaop.WebLogAspect  : HTTP_METHOD:GET
2020-06-28 10:38:22.195  INFO [fec-expense,,,] 35428 --- [  XNIO-1 task-1] c.h.hcf.app.expense.logaop.WebLogAspect  : IP    :10.72.9.128
2020-06-28 10:38:22.196  INFO [fec-expense,,,] 35428 --- [  XNIO-1 task-1] c.h.hcf.app.expense.logaop.WebLogAspect  : CLASS_METHOD:com.hand.hcf.app.expense.report.web.ExpenseReportController.getExpenseReportLinesByHeaderId
2020-06-28 10:38:22.197  INFO [fec-expense,,,] 35428 --- [  XNIO-1 task-1] c.h.hcf.app.expense.logaop.WebLogAspect  : ARGS:[1199962780901412865, Page request [number: 0, size 5, sort: UNSORTED]]

 

二、oauth2+redis+分布式定时任务来备份所有服务的请求

         实现原理:

        1.在微服务架构体系中,每个服务的请求都会进行认证,可以通过 oauth2将每个服务的请求均需要定向到auth服务去鉴权。

        2.使用redis将所有访问的请求给缓存起来,避免过多请求给数据库造成访问压力。

        3.使用定时任务将redis服务器里的一定时间内的所有请求给备份到数据库中。

security.oauth2.client.access-token-uri = http://fec-api-gateway-uat.internal.aegonthtf.com/fec-auth/oauth/token
security.oauth2.client.client-authentication-scheme = form
security.oauth2.client.client-id = implement-integration
security.oauth2.client.client-secret = K2QzPPz3fqQNEnsbwupD1b1IDPPg0RfkdWalXysL7wd
security.oauth2.client.grant-type = client_credentials
security.oauth2.resource.user-info-uri =http://fec-api-gateway-uat.internal.aegonthtf.com/fec-auth/api/check_token

          利用oauth2的特性,可以将 所有的访问请求重定向到/api/check_token上去鉴权,那么所有的请求都会在这个接口上。

       oauth2的版本为:

 <dependency>
            <groupId>org.springframework.security.oauth.boot</groupId>
            <artifactId>spring-security-oauth2-autoconfigure</artifactId>
            <version>2.1.3.RELEASE</version>
</dependency>

 
<dependency>
       <groupId>org.springframework.security.oauth</groupId>
       <artifactId>spring-security-oauth2</artifactId>
       <version>2.3.5.RELEASE</version>
 </dependency>

   <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-data</artifactId>
  </dependency>

   



package com.hand.hcf.app.auth.web;

import com.hand.hcf.app.auth.service.UserService;
import com.hand.hcf.core.exception.core.UnauthenticatedException;
import com.hand.hcf.core.security.domain.Authority;
import com.hand.hcf.core.security.domain.PrincipalLite;
import jline.internal.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api")
public class AccountResource {
    @Autowired
    private UserService userService;
    @GetMapping(value = "/check_token")
    public PrincipalLite checkToken() {
        if (SecurityContextHolder.getContext().getAuthentication() instanceof OAuth2Authentication) {
            OAuth2Authentication auth2Authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
            if (auth2Authentication.getUserAuthentication() != null) {
                if (auth2Authentication.getPrincipal() instanceof Map) {
                    Log.info("auth2Authentication is map");
                }
                //备份请求
                userService.backRequest();
                return (PrincipalLite) auth2Authentication.getPrincipal();
            } else {
                String clientId = auth2Authentication.getOAuth2Request().getClientId();
                PrincipalLite principalLite = userService.getUserByOauthClientId(clientId);
                if(null == principalLite){
                    principalLite = new PrincipalLite();
                }
                principalLite.setLogin((String) auth2Authentication.getPrincipal());
                principalLite.setAuthorities(auth2Authentication.getAuthorities().stream().map(right -> new Authority(right.getAuthority())).collect(Collectors.toSet()));
                userService.backRequest();
                return principalLite;
            }

        } else {
            throw new UnauthenticatedException();
        }

    }
}

    

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章