Log4j2日志依赖
<!-- log4j2 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
需要去掉SpringBoot本身的日志配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions><!-- 去掉springboot默认配置 -->
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
Log4j2的配置文件( log4j2-spring.xml )
<?xml version="1.0" encoding="UTF-8"?>
<configuration monitorInterval="5">
<!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<!--变量配置-->
<Properties>
<!-- 格式化输出:%date表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度 %msg:日志消息,%n是换行符-->
<!-- %logger{36} 表示 Logger 名字最长36个字符 -->
<property name="LOG_PATTERN" value="%date{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n" />
<!-- 定义日志存储的路径,不要配置相对路径 -->
<property name="FILE_PATH" value="E:\Program\logs" />
<property name="FILE_NAME" value="demo" />
</Properties>
<appenders>
<console name="Console" target="SYSTEM_OUT">
<!--输出日志的格式-->
<PatternLayout pattern="${LOG_PATTERN}"/>
<!--控制台只输出level及其以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
<ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
</console>
<!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,适合临时测试用-->
<File name="Filelog" fileName="${FILE_PATH}/test.log" append="false">
<PatternLayout pattern="${LOG_PATTERN}"/>
</File>
<!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
<RollingFile name="RollingFileInfo" fileName="${FILE_PATH}/info.log" filePattern="${FILE_PATH}/${FILE_NAME}-INFO-%d{yyyy-MM-dd}_%i.log.gz">
<!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
<ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout pattern="${LOG_PATTERN}"/>
<Policies>
<!--interval属性用来指定多久滚动一次,默认是1 hour-->
<TimeBasedTriggeringPolicy interval="1"/>
<SizeBasedTriggeringPolicy size="10MB"/>
</Policies>
<!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件开始覆盖-->
<DefaultRolloverStrategy max="15"/>
</RollingFile>
<!-- 这个会打印出所有的warn及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
<RollingFile name="RollingFileWarn" fileName="${FILE_PATH}/warn.log" filePattern="${FILE_PATH}/${FILE_NAME}-WARN-%d{yyyy-MM-dd}_%i.log.gz">
<!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
<ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout pattern="${LOG_PATTERN}"/>
<Policies>
<!--interval属性用来指定多久滚动一次,默认是1 hour-->
<TimeBasedTriggeringPolicy interval="1"/>
<SizeBasedTriggeringPolicy size="10MB"/>
</Policies>
<!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件开始覆盖-->
<DefaultRolloverStrategy max="15"/>
</RollingFile>
<!-- 这个会打印出所有的error及以下级别的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
<RollingFile name="RollingFileError" fileName="${FILE_PATH}/error.log" filePattern="${FILE_PATH}/${FILE_NAME}-ERROR-%d{yyyy-MM-dd}_%i.log.gz">
<!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
<ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="DENY"/>
<PatternLayout pattern="${LOG_PATTERN}"/>
<Policies>
<!--interval属性用来指定多久滚动一次,默认是1 hour-->
<TimeBasedTriggeringPolicy interval="1"/>
<SizeBasedTriggeringPolicy size="10MB"/>
</Policies>
<!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件开始覆盖-->
<DefaultRolloverStrategy max="15"/>
</RollingFile>
</appenders>
<!--Logger节点用来单独指定日志的形式,比如要为指定包下的class指定不同的日志级别等。-->
<!--然后定义loggers,只有定义了logger并引入的appender,appender才会生效-->
<loggers>
<!--过滤掉spring和mybatis的一些无用的DEBUG信息-->
<logger name="org.mybatis" level="info" additivity="false">
<AppenderRef ref="Console"/>
</logger>
<!--监控系统信息-->
<!--若是additivity设为false,则 子Logger 只会在自己的appender里输出,而不会在 父Logger 的appender里输出。-->
<Logger name="org.springframework" level="info" additivity="false">
<AppenderRef ref="Console"/>
</Logger>
<root level="info">
<appender-ref ref="Console"/>
<appender-ref ref="Filelog"/>
<appender-ref ref="RollingFileInfo"/>
<appender-ref ref="RollingFileWarn"/>
<appender-ref ref="RollingFileError"/>
</root>
</loggers>
</configuration>
工具类
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import sun.reflect.Reflection;
import java.util.Date;
public class LoggerUtil {
private static boolean isLog = true;
private static Logger logger = null;
public static void setLogger(boolean isLog) {
LoggerUtil.isLog = isLog;
}
public static void setLog(Logger logger) {
LoggerUtil.logger = logger;
}
public static void setLogger(Logger logger) {
LoggerUtil.logger = logger;
}
public static void debug(Object msg) {
if (isLog) {
if (logger == null) {
StackTraceElement[] stackTraceElement = Thread.currentThread().getStackTrace();
if (stackTraceElement.length > 3) {
logger = LogManager.getLogger(stackTraceElement[2].getClassName());
logger.debug("调用者类名" + stackTraceElement[2].getClassName());
} else {
logger = LogManager.getLogger(Reflection.getCallerClass(2).getName());
logger.debug("调用者类名" + Reflection.getCallerClass(2).getName());
}
}
logger.debug(new Date() + " " + msg);
}
}
public static void info(Object msg) {
if (isLog) {
if (logger == null) {
StackTraceElement[] stackTraceElement = Thread.currentThread().getStackTrace();
if (stackTraceElement.length > 3) {
logger = LogManager.getLogger(stackTraceElement[2].getClassName());
logger.debug("调用者类名" + stackTraceElement[2].getClassName());
} else {
logger = LogManager.getLogger(Reflection.getCallerClass(2).getName());
logger.debug("调用者类名" + Reflection.getCallerClass(2).getName());
}
}
logger.info(new Date() + " " + msg);
}
}
public static void warn(Object msg) {
if (isLog) {
if (logger == null) {
StackTraceElement[] stackTraceElement = Thread.currentThread().getStackTrace();
if (stackTraceElement.length > 3) {
logger = LogManager.getLogger(stackTraceElement[2].getClassName());
logger.debug("调用者类名" + stackTraceElement[2].getClassName());
} else {
logger = LogManager.getLogger(Reflection.getCallerClass(2).getName());
logger.debug("调用者类名" + Reflection.getCallerClass(2).getName());
}
}
logger.warn(new Date() + " " + msg);
}
}
public static void error(Object msg) {
if (isLog) {
if (logger == null) {
StackTraceElement[] stackTraceElement = Thread.currentThread().getStackTrace();
if (stackTraceElement.length > 3) {
logger = LogManager.getLogger(stackTraceElement[2].getClassName());
logger.debug("调用者类名" + stackTraceElement[2].getClassName());
} else {
logger = LogManager.getLogger(Reflection.getCallerClass(2).getName());
logger.debug("调用者类名" + Reflection.getCallerClass(2).getName());
}
}
logger.error(new Date() + " " + msg);
}
}
public static void fatal(Object msg) {
if (isLog) {
if (logger == null) {
StackTraceElement[] stackTraceElement = Thread.currentThread().getStackTrace();
if (stackTraceElement.length > 3) {
logger = LogManager.getLogger(stackTraceElement[2].getClassName());
logger.debug("调用者类名" + stackTraceElement[2].getClassName());
} else {
logger = LogManager.getLogger(Reflection.getCallerClass(2).getName());
logger.debug("调用者类名" + Reflection.getCallerClass(2).getName());
}
}
logger.fatal(new Date() + " " + msg);
}
}
}
切面依赖
<!--aspect切面-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
默认用法(自用)
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.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
@Aspect
@Component
public class ControllerAspect {
@Pointcut("execution(* com.tr.demo.controller..*.*(..))")
public void one(){}
@Around("one()")
public Object handle(ProceedingJoinPoint pjp) throws Throwable {
Object[] args = pjp.getArgs();
//获取请求参数
//controller参数均为Map<Object,String>类型,所以进行强转
Map<Object,String> map=(Map<Object, String>) args[0];
//获取请求头
HttpServletRequest request= (HttpServletRequest) args[1];
//日志输出
LoggerUtil.info("\nIP:"+request.getRemoteAddr()+"\n调用接口:"+request.getRequestURI()+"\n接口参数为:"+map);
//空参数检查
if(map.isEmpty()){
resp.setResp(-1,null,"空参数!");
return resp;
}else {
Object object = pjp.proceed();
return object;
}
}
@AfterReturning(value = "one()",returning = "resp")
public void afterReturning(Object resp){
//结果输出
LoggerUtil.info("\n调用结果"+resp);
}
}
mysql的驱动
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/
spring.datasource.username=用户名
spring.datasource.password=密码
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
mybatis-plus依赖
配置
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
数据库连接池
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
<!--数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.20</version>
</dependency>
JWT依赖
拦截器配置
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sass.studentactivityscoresystem.entity.RespBody;
import com.sass.studentactivityscoresystem.entity.User;
import com.sass.studentactivityscoresystem.mapper.UserMapper;
import com.sass.studentactivityscoresystem.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
public class JwtInterceptor implements HandlerInterceptor {
@Autowired
UserMapper userMapper;
@Autowired
RespBody respBody;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
// 从 http 请求头中取出 token
String token = request.getHeader("token");
// 如果不是映射到方法直接通过
if(!(handler instanceof HandlerMethod)){
return true;
}
if (StringUtils.isBlank(token)) {
respBody.setResp(401,null,"用户未登录,请登录");
PrintWriter writer = response.getWriter();
writer.print(respBody.Oj2Json());
writer.close();
return false;
}else {
// 获取 token中的userId,检查用户是否存在
String userId;
try {
userId = JWT.decode(token).getAudience().get(0);
} catch (JWTDecodeException j) {
respBody.setResp(400,null,"token错误");
PrintWriter writer = response.getWriter();
writer.print(respBody.Oj2Json());
writer.close();
return false;
}
User user = userMapper.selectById(userId);
if (user == null) {
respBody.setResp(400,null,"用户不存在,请重新登录");
PrintWriter writer = response.getWriter();
writer.print(respBody.Oj2Json());
writer.close();
return false;
}else {
// 验证 token
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(JwtUtils.getSk())).build();
try {
jwtVerifier.verify(token);
} catch (JWTVerificationException e) {
respBody.setResp(401,null,"登录已经失效,请重新登录");
PrintWriter writer = response.getWriter();
writer.print(respBody.Oj2Json());
writer.close();
return false;
}
}
}
return true;
}
}
<!--JWT-->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.0</version>
</dependency>
JSON
<!--JSON工具-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
博主真是太厉害了!!!