Add aspect to surround notification implementation, and the log is more complete.

 

Add aspect to surround notification implementation, and the log is more complete.

1. Configure the corresponding log framework, and manually log where needed (consumer and server are configured in this way)

 

 

 1. Add dependency packages Logback needs to be used with slf4j, so the total packages that need to be added are slf4j-api

The use of logback needs to be used together with slf4j, so the total dependencies that need to be added are slf4j-api.jar, logback-core.jar, logback-classic.jar, logback-access.jar. This is temporarily unavailable, so no dependencies are added. maven configuration

  <properties>

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    <logback.version>1.1.7</logback.version>

    <slf4j.version>1.7.21</slf4j.version>

  </properties>

 

  <dependencies>

    <dependency>

      <groupId>org.slf4j</groupId>

      <artifactId>slf4j-api</artifactId>

      <version>${slf4j.version}</version>

      <scope>compile</scope>

    </dependency>

    <dependency>

      <groupId>ch.qos.logback</groupId>

      <artifactId>logback-core</artifactId>

      <version>${logback.version}</version>

    </dependency>

    <dependency>

      <groupId>ch.qos.logback</groupId>

      <artifactId>logback-classic</artifactId>

      <version>${logback.version}</version>

      </dependency>

  </dependencies>

 

  2. logback.xml configuration

<?xml version="1.0" encoding="UTF-8"?>

<configuration debug="false">

<!--Define the storage address of log files Do not use relative paths in the configuration of LogBack-->

<property name="LOG_HOME" value="/home" />

<!-- console output -->

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">

<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">

<!--Formatted output: %d means date, %thread means thread name, %-5level: level displays 5 characters width from left %msg: log message, %n is newline -->

<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>

</encoder>

</appender>

<!-- Generate log files on a daily basis-->

<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">

<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">

<!--The file name of the log file output-->

<FileNamePattern>${LOG_HOME}/TestWeb.log.%d{yyyy-MM-dd}.log</FileNamePattern>

<!--Number of days to keep log files-->

<MaxHistory>30</MaxHistory>

</rollingPolicy>

<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">

<!--Formatted output: %d means date, %thread means thread name, %-5level: level displays 5 characters width from left %msg: log message, %n is newline -->

<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>

</encoder>

<!--Maximum size of log file-->

<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">

<MaxFileSize>10MB</MaxFileSize>

</triggeringPolicy>

</appender>

 

<!-- log output level-->

<root level="INFO">

<appender-ref ref="STDOUT" />

</root>

</configuration>

 

  3. java code

  /**

  * Hello world!

  */

  public class App {

 

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

 

    public static void main(String[] args) {

      logger.info("logback succeeded");

      logger.error("logback succeeded");

      logger.debug("logback succeeded");

    }

  }

 

 

refer to:

https://www.cnblogs.com/warking/p/5710303.html

 

2. On the basis of 1, configure the aspect --- "Using the aspect, surrounding notifications, automatic interception,

Generally used to print requests, parameters, and return results (not interceptors)

This can make up for the problem of insufficient set points in 1, so that temporary debugging does not require continuous points

 

This LogAopAspect is the aspect, where the notification is implanted into the defined pointcut

@Component incorporates classes into spring, @Aspect annotation defines aspects, and xml startup annotation scanning needs to be defined

@Pointcut defines pointcut (program normal method)

@Around defines the advice, where the advice is implanted into the pointcut (the method of advice modification)

 

 

 

Consumer:

 

 

package com.houbank.incoming.web.interceptor;

 

import java.util.HashMap;

import java.util.Map;

 

import javax.servlet.http.HttpServletRequest;

 

import org.aspectj.lang.ProceedingJoinPoint;

import org.aspectj.lang.annotation.Around;

import org.aspectj.lang.annotation.Aspect;

import org.aspectj.lang.annotation.Pointcut;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

 

import com.alibaba.druid.support.spring.mvc.StatHandlerInterceptor;

import com.alibaba.fastjson.JSON;

 

/**

 * 

 * <p>Custom log interception class</p>

 * @author houzhanshan

 * @version $Id: LogAopAspect.java, v 0.1 Jun 5, 2017 10:08:19 AM Exp $

 */

@Component

@Aspect

public class LogAopAspect {

 

    public static final String REQUESTIP     = "requestIp";

 

    public static final String REQUESTPORT   = "requestPort";

 

    public static final String REQUESTURI    = "requestUri";

 

    public static final String REQUESTTYPE   = "requestType";

 

    public static final String REQUEST_PARAM = "param";

 

    @Pointcut("execution(* com.houbank.incoming.web.controller..*(..)) and  @within(org.springframework.web.bind.annotation.Controller)")

    private void anyAcesssAndResponseMethdod() {

    }

 

    @Autowired

    private HttpServletRequest request;

 

    @Around("anyAcesssAndResponseMethdod()")

    public Object notifyLog(ProceedingJoinPoint joinPoint) throws Throwable {

        Object returnObj = null;

        if (joinPoint.getArgs().length > 0) {

            Map<String, Object> paramMap = new HashMap<>();

            paramMap.put(REQUESTIP, request.getServerName());

            paramMap.put(REQUESTPORT, String.valueOf(request.getServerPort()));

            paramMap.put(REQUESTURI, request.getRequestURI());

            paramMap.put(REQUESTTYPE, request.getMethod());

            paramMap.put(REQUEST_PARAM, JSON.toJSONString(request.getParameterMap()));

            LogUtils.accessLog.info("request" + JSON.toJSONString(paramMap));

           returnObj = joinPoint.proceed();//Implanted pointcut

            if (returnObj != null) {

                LogUtils.accessLog.info("返回response" + JSON.toJSONString(returnObj));

            }

            return returnObj;

 

        } else {

            Map<String, Object> paramMap = new HashMap<>();

            paramMap.put(REQUESTIP, request.getServerName());

            paramMap.put(REQUESTPORT, String.valueOf(request.getServerPort()));

            paramMap.put(REQUESTURI, request.getRequestURI());

            paramMap.put(REQUESTTYPE, request.getMethod());

            LogUtils.accessLog.info("return request" + JSON.toJSONString(paramMap));

            returnObj = joinPoint.proceed();

            if (returnObj != null) {

                LogUtils.accessLog.info("返回response" + JSON.toJSONString(returnObj));

            }

 

        }

        return returnObj;

 

    }

    

    

    static class AccessLog {

        private static Logger logger;

            

            public static Logger getLogger(String name) {

                logger = LoggerFactory.getLogger(name);

                return logger;

            }

        }

 

}

 

 

xml

 

To configure slice annotation scanning:

 

<?xml version="1.0" encoding="UTF-8"?>

<!--

proxy configuration

-->

<beans xmlns="http://www.springframework.org/schema/beans"

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xmlns:aop="http://www.springframework.org/schema/aop"

       xsi:schemaLocation="http://www.springframework.org/schema/beans

           http://www.springframework.org/schema/beans/spring-beans.xsd

           http://www.springframework.org/schema/aop

           http://www.springframework.org/schema/aop/spring-aop.xsd">

 

    <!-- Interceptor --><!-- Enable support for @AspectJ annotation -->

    <aop:aspectj-autoproxy/>

    

</beans>

 

 

 

 

 

 

Server:

 

@Component is included in spring management, @Aspect defines aspects, and xml needs to configure aspect scanning

@Pointcut defines the pointcut

@Before pre-notification, @AfterReturning post-notification

 

 

 

 

 

 

 

package com.houbank.incoming.service.log;

 

import java.lang.reflect.Method;

 

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.aspectj.lang.reflect.MethodSignature;

import org.springframework.stereotype.Component;

 

import lombok.extern.slf4j.Slf4j;

 

@Aspect

@Component

@ Slf4j

public class LogAspect {

 

@Pointcut("execution(* com.houbank.incoming.service.impl.*.*(..))")  

    public void methodPointcut() {}

 

@Before("methodPointcut()")

    public void before(JoinPoint joinPoint) {

        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();

        // The query does not record the log

        if(method.getName().startsWith("select") || method.getName().startsWith("get") || method.getName().startsWith("query")) {

        return;

        }

        StringBuilder sb = new StringBuilder();

        sb.append(method.getDeclaringClass().getSimpleName()).append(".").append(method.getName()).append(" req:");

        for(int i = 0; i < joinPoint.getArgs().length; i++) {

        sb.append(joinPoint.getArgs()[i]);

        }

        log.info(sb.toString());

    }

 

@AfterReturning(returning="rvt", pointcut="methodPointcut()")

    public void after(JoinPoint joinPoint, Object rvt) {

        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();

        // The query does not record the log

        if(method.getName().startsWith("select") || method.getName().startsWith("get") || method.getName().startsWith("query")) {

        return;

        }

        log.info(method.getDeclaringClass().getSimpleName() + "."+ method.getName() + " resp:" + rvt);

    }

}

 

 

 

 

 

 

 

 

 

 

 

xml placement:

 

<!-- Enable support for @AspectJ annotation -->

    <aop:aspectj-autoproxy proxy-target-class="true"/>

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326085487&siteId=291194637