Spring Boot from entry to actual combat: Integrated AOPLog access log to record interface

Web logs are a necessary part of the project, by means of which we can do many things, such as troubleshooting, access statistics, monitor alarms. Typically done by introducing some implementations, the frame slf4j logging, such as log4j, logback, log4j2, its performance is enhanced in turn. In springboot, the default is to use the framework logback. We often need to record at the beginning or end of the method add log incoming parameters or return results, in order to reproduce the situation at the time of request. However, manually add the log, not only tedious repetition, but also affect the appearance of simple code. This paper introduces a logging framework AOP-based implementation, and integration is accomplished by spring-boot-starter manner.

Original Address: http://blog.jboost.cn/2019/06/27/springboot-aoplog.html

1. aop-logging project

Project Address:  https://github.com/ronwxy/aop-logging
The project is based on  https://github.com/nickvl/aop-logging.git  , on the basis of its ReqId added to the series a particular client request ( reference com.github.nickvl.xspring.core.log.aop.ReqIdFilter), was added a length (refer to performing the methods of com.github.nickvl.xspring.core.log.aop.AOPLogger.logTheMethodthe method elapsedTime).

The project provides annotation-based AOP logging. Depending on the logging level, provides annotations are LogTrace, LogDebug, LogInfo, LogWarn, LogError, LogFatal, LogException, the class may be modified (added all equivalent methods within the class) and the method, respectively, in front of six different recording method is called a log under the log level, LogException said in a method throws an exception, the corresponding log record. These annotations provide a LogPoint enumerated property value, the value {IN, OUT, BOTH}, respectively, in the process of calling the inlet, before the method call returns, and including the position corresponding to both printing logs, the default is BOTH.

2. Integration

Xml-based or may be based on an integrated manner java AOP logging configuration, where I java-based configuration (xml-based manner as in Reference source README file) and encapsulated (source address in the form of a spring-boot-starter:  HTTPS: // github.com/ronwxy/base-spring-boot  ), to avoid the need to configure each project. Automatically configured following class

@Configuration
@ConditionalOnClass(AOPLogger.class)
@ConditionalOnMissingBean(AOPLogger.class)
public class AopLoggerAutoConfiguration {

    private static final boolean SKIP_NULL_FIELDS = true;
    private static final Set<String> EXCLUDE_SECURE_FIELD_NAMES = Collections.emptySet();

    @Bean
    public AOPLogger aopLogger() {
        AOPLogger aopLogger = new AOPLogger();
        aopLogger.setLogAdapter(newUniversalLogAdapter (SKIP_NULL_FIELDS, EXCLUDE_SECURE_FIELD_NAMES));
         return aopLogger; 
    } 

    / ** 
    * register a filter for generating a reqId, marking a request to log this request generated concatenated 
    * @param 
    * @return 
    * / 
    @Bean 
    public FilterRegistrationBean reqIdFilter () { 
        ReqIdFilter reqIdFilter = new new ReqIdFilter (); 
        FilterRegistrationBean registrationBean = new new FilterRegistrationBean (); 
        registrationBean.setFilter (reqIdFilter); 
        List <String> urlPatterns = Collections.singletonList ( "/ *" );
        registrationBean.setUrlPatterns(urlPatterns);
        registrationBean.setOrder(100);
        return registrationBean;
    }
}

 

The base frame by base-spring-boot mvn clean installafter local installation, can be introduced by the project-dependent (base frame has been incorporated in the spring-boot-parent, also inherits directly), such as

<dependency>
   <groupId>cn.jboost.springboot</groupId>
   <artifactId>aoplog-spring-boot-starter</artifactId>
   <version>1.2-SNAPSHOT</version>
</dependency>

 

3. Use 

After the introduction of dependence, we then define a configuration log file logback-spring.xml, in order to facilitate later introduction ELK log log analysis do centralized management of the profile in the log json output format, and written to the log in accordance with each level debug.log, info.log, warn.log, error.log and interface.log (dedicated access log to the interface), as a configuration example (refer to the complete configuration:  https://github.com/ronwxy/springboot-demos/blob /master/springboot-aoplog/src/main/resources/logback-spring.xml)

<appender name="interfaceLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${logPath}/elk/interface.log</file>
        <encoder class="net.logstash.logback.encoder.LoggingEventCompositeJsonEncoder">
            <providers>
                <pattern>
                    <pattern>
                        {
                        "project": "${projectName}",
                        "timestamp": "%date{\"yyyy-MM-dd'T'HH:mm:ss,SSSZ\"}",
                        "log_level": "%level",
                        "thread": "%thread",
                        "class_name": "%X{callingClass}",
                        "class_method":"%X{callingMethod}",
                        "line_number": null,
                        "message": "%message",
                        "stack_trace": "%exception{5}",
                        "req_id": "%X{reqId}",
                        "elapsed_time": "#asLong{%X{elapsedTime}}"
                        }
                    </pattern>
                </pattern>
            </providers>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>INFO</level>
        </filter>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${logPath}/bak/interface.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>30</maxHistory>
            <totalSizeCap>1GB</totalSizeCap>
        </rollingPolicy>
    </appender>

 

To the log file can be configured without modification to achieve reuse, some of the external parameters, it is required to set the parameters in the configuration file applicaiton.yml 

Logger: 
  path: D: \ logs # default logs directory under the current project path 
  level: info # default info 
  apiPackage: cn.jboost.springboot.aoplog.controller # must be configured, api interface class where the package 
  rootPackage: cn.jboost.springboot # You must configure the project root package, logging within the package through various types of output slf4j

 

Finally, the need to record directly on the interface class annotated @LogInfo access log on the line, such as 

@RestController
@RequestMapping("test")
@LogInfo
public class AoplogTestController {

    @GetMapping
    public String test(@RequestParam String user){
        return "Hi " + user;
    }
}

 

NOTE: to add a goal repackage the spring-boot-maven-plugin in pom.xml added by default to automatically generate log files and log directory, as shown in FIG. 

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

 

 Start a program, when the API calls in the interface class @LogInfo marked, you can see the console interface to access the print log, such as the implementation of demo program (Source:  https://github.com/ronwxy/springboot-demos/tree/master / springboot-aoplog  ), call  http: // localhost:? 8080 / test user = jboost  , the console print log is as follows

[2019-06-27 14:29:59] [INFO ] [http-nio-8080-exec-1] [cn.jboost.springboot.aoplog.controller.AoplogTestController:184] --calling: test(user=jboost)
[2019-06-27 14:29:59] [INFO ] [http-nio-8080-exec-1] [cn.jboost.springboot.aoplog.controller.AoplogTestController:189] --returning: test(1 arguments):Hi jboost

Interface.log printing log in the log file as follows (the same in all of which req_id log this request, so that all the logs can be a request together, to facilitate analysis and positioning problems; marked long elapsed_time method performed, it may be used performance monitoring Interface)

{"project":"aoplog-test","timestamp":"2019-06-27T14:29:59,030+0800","log_level":"INFO","thread":"http-nio-8080-exec-1","class_name":"cn.jboost.springboot.aoplog.controller.AoplogTestController","class_method":"test","line_number":null,"message":"calling: test(user=jboost)","stack_trace":"","req_id":"5d146267aa147904bc014e71","elapsed_time":null}
{"project":"aoplog-test","timestamp":"2019-06-27T14:29:59,036+0800","log_level":"INFO","thread":"http-nio-8080-exec-1","class_name":"cn.jboost.springboot.aoplog.controller.AoplogTestController","class_method":"test","line_number":null,"message":"returning: test(1 arguments):Hi jboost","stack_trace":"","req_id":"5d146267aa147904bc014e71","elapsed_time":2}

 

4. Summary 

Web projects often need to locate the problem by looking at the interface requests and return parameters, write code print seem tedious and repetitive manual. Can be realized by a simple interface to automatically print the log notes using aop-logging. Programs and log configuration template described in this article can be used directly in the actual project development. Of course, not only for annotations Controller layer, other layers may also be used for other Service, but generally can be coupled Controller layer, to avoid excessive log printing.

This paper sample project Source Address: https://github.com/ronwxy/springboot-demos/tree/master/springboot-aoplog


my personal blog address: http://blog.jboost.cn
my github address: HTTPS: / /github.com/ronwxy
my micro-channel public number: jboost-ksxy (welcome attention, timely access to technical dry goods
share) ------------------------- ---------

Micro-channel public number
I welcome attention to the micro-channel public number, timely access to the latest share

Guess you like

Origin www.cnblogs.com/spec-dog/p/11097239.html