Catalog
One: Logging System in java Web Project
II: Classification of Logging Systems
3: springboot integrates slf4j
2. Configuring xml and developing yml
IV: Logging using Aop method, and asynchronous method to execute logging
1. Define an asynchronous thread pool
2. Generate asynchronous method on log insertion
3. Encapsulating log objects around notifications
One: Logging System in java Web Project
In B/S architecture, log system is an important part of the system. A clear and clear log system can help us quickly locate the point, time and cause of the problem. In the Internet project production environment, there are many exceptions or errors that can not be reproduced but are extremely serious. At the same time, some user logs can help us analyze user habits and interests. Therefore, the design of a reasonable log framework is particularly important. (The following includes the following contents are all personal talk, if you have questions, I hope to raise them.)
In a system, logs are generally divided into two types: system logs and operation logs. The various classifications and uses are as follows:
System Log: Used to record system behavior and locate problems quickly.
System Behavior: Link log used to record system operation.
Abnormal log: location of abnormal occurrence.
Error log: Error location.
Operational log: Used to record user's behavior in order to analyze user's behavior, interest, etc. (especially important in Internet projects).
So much, let's go straight to a mind map for easy understanding.
II: Classification of Logging Systems
In java, we encounter many log frameworks more or less: log4j,log4j2,slf4j and so on.
General logging frameworks are simply divided into two categories:
Log facade: commons-logging,slf4j
Log implementation: log4j,log4j2,logback
Undoubtedly, once multiple log frameworks are introduced into the project, conflicts will arise. In fact, a solution is used to resolve conflicts in the log system: the log system bridge. The log system bridge uses the log facade to forcibly hijack other log frameworks into the implementation of the facade framework.
3: springboot integrates slf4j
1. Add mavne support
<!-- Logging Tool Class --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </dependency>
2. Configuring xml and developing yml
<?xml version="1.0" encoding="UTF-8"?> <configuration> <property name="log.path" value="./fangList_logs" /> <property name="log.pattern" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n" /> <!-- console output --> <appender name="console" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern>${log.pattern}</pattern> </encoder> </appender> <!-- System log output --> <appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${log.path}/sys-info.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- Rollback by day daily --> <fileNamePattern>${log.path}/sys-info.%d{yyyy-MM-dd}.log</fileNamePattern> <!-- The History of the Largest Log: 60 Days --> <maxHistory>60</maxHistory> </rollingPolicy> <encoder> <pattern>${log.pattern}</pattern> </encoder> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>INFO</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> </appender> <appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${log.path}/sys-error.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${log.path}/sys-error.%d{yyyy-MM-dd}.log</fileNamePattern> <!-- The History of the Largest Log: 60 Days --> <maxHistory>60</maxHistory> </rollingPolicy> <encoder> <pattern>${log.pattern}</pattern> </encoder> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>ERROR</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> </appender> <!-- User Access Log Output --> <appender name="sys-user" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${log.path}/sys-user.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- Rollback by day daily --> <fileNamePattern>${log.path}/sys-user.%d{yyyy-MM-dd}.log</fileNamePattern> <!-- The History of the Largest Log: 60 Days --> <maxHistory>60</maxHistory> </rollingPolicy> <encoder> <pattern>${log.pattern}</pattern> </encoder> </appender> <!-- Displaying sql,Used parameters, result sets --> <logger name="java.sql" level="debug" /> <logger name="org.springframework.jdbc" level="debug" /> <logger name="cn.com" level="info" /> <root level="info"> <appender-ref ref="console" /> </root> <!--System Operation Log--> <root level="info"> <appender-ref ref="file_info" /> <appender-ref ref="file_error" /> </root> <!--System user operation log--> <logger name="sys-user" level="info"> <appender-ref ref="sys-user"/> </logger> </configuration>
logging: level: com.moudle.user.dao: debug org.springframework: WARN org.spring.springboot.dao: debug
3. Code testing
4. Logging
IV: Logging using Aop method, and asynchronous method to execute logging
The above mainly illustrates the integration of slf4j into spring boot, and the following Aop format is used to process logs.
1. Define an asynchronous thread pool
package commons.utils.Thread; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; /** * springboot Asynchronous thread pool * @author Owner * */ @EnableAsync @Configuration class TaskPollConfig{ @Bean("taskExecutor") public Executor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(10); executor.setMaxPoolSize(20); executor.setQueueCapacity(200); executor.setKeepAliveSeconds(60); executor.setThreadNamePrefix("taskExecutor-"); executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.setWaitForTasksToCompleteOnShutdown(true); executor.setAwaitTerminationSeconds(60); return executor; } }
2. Generate asynchronous method on log insertion
I have some other unprocessed log inserts here, which are suitable for inserting users to simulate.
3. Encapsulating log objects around notifications
package com.config.Aspect.log; import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.catalina.servlet4preview.http.HttpServletRequest; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Around; 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.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import commons.json.JSON; import commons.result.DataResult; import lombok.extern.java.Log; import lombok.extern.slf4j.Slf4j; /** * Log section * ClassName: LogAscpect * Function: One sentence describes the function. * auth: monxz * date: 2019 September 18, 3:46:23 p.m. * * */ @Aspect @Component @Slf4j public class LogAscpect { @Pointcut("execution(public * com.moudle.*.controller.*.*(..))") public void sysLog() {} @Around("sysLog()") public Object saveSysLog(ProceedingJoinPoint proceedingJoinPoint) { //A Method of Obtaining Weaving Point from the Weaving Point of Cut Surface by Reflection Mechanism MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature(); //The way to get the entry point Method method = signature.getMethod(); //Get the class name of the request String className = proceedingJoinPoint.getTarget().getClass().getName(); //Get the method name of the request String methodName = method.getName(); //Request parameters Object[] args = proceedingJoinPoint.getArgs(); //Get the username //Get the user's ip address // Receive the request and record the content of the request ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = (HttpServletRequest) attributes.getRequest(); // Record the content of the request log.info("URL : " + request.getRequestURL().toString()); log.info("HTTP_METHOD : " + request.getMethod()); log.info("IP : " + request.getRemoteAddr()); /** * * TODO:Encapsulate the above parameters as log objects and insert logs * */ //Initiation time // Timing and calling the target function long start = System.currentTimeMillis(); Long time = System.currentTimeMillis() - start; Object result ; try { result= proceedingJoinPoint.proceed(); return result; } catch (Throwable e) { e.printStackTrace(); return new DataResult().buildFail("Systematic anomaly"); } } }
4. Description
Here we insert the log asynchronously without affecting the running of the main program.