配置日志级别
(1)日志记录器(Logger)的行为是分等级的。分为:OFF、FATAL、ERROR、WARN、INFO、DEBUG、ALL
(2)默认情况下,spring boot从控制台打印出来的日志级别只有INFO及以上级别,可以配置日志级别
(3)在application.properties中配置日志级别
# 设置日志级别
logging.level.root=WARN
Logback日志工具
(1)spring boot内部也是使用Logback作为日志实现的框架
(2)日志不仅能输出到控制台,也可以输出到文件中,可以使用Logback日志工具来实现
配置logback日志
(1)删除application.properties中的日志配置
#mybatis日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#设置日志级别
logging.level.root=INFO
(2)在resources中创建logback-spring.xml,里面的写法是固定的
<property name="log.path" value="E:/work/guli_log/edu" />
如果程序运行出现异常,把异常信息输出到文件中
(1)在统一异常处理类GlobalExceptionHandler中添加注解 @Slf4j
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
...
@ExceptionHandler(GuliException.class) // 自定义异常
@ResponseBody
public R error(GuliException e) {
log.error(e.getMessage()); // 异常输出语句,e.getMessage()写到error里面去
e.printStackTrace();
return R.error().code(e.getCode()).message(e.getMsg());
}
}
可以定义工具类将日志堆栈信息输出到文件,得到更详细的信息
(1)com.guli.common下创建util包,创建ExceptionUtil.java工具类
public class ExceptionUtil {
public static String getMessage(Exception e) {
StringWriter sw = null;
PrintWriter pw = null;
try {
sw = new StringWriter();
pw = new PrintWriter(sw);
e.printStackTrace(pw); // 将出错的栈信息输出到printWriter中
pw.flush();
sw.flush();
} finally {
if (sw != null) {
try {
sw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (pw != null) {
pw.close();
}
}
return sw.toString();
}
}
(2)GuliException中创建toString方法
@Override
public String toString() {
return "GuliException{" +
"message=" + this.getMessage() +
", code=" + code +
'}';
}
(3)调用
@ExceptionHandler(GuliException.class) // 自定义异常
@ResponseBody
public R error(GuliException e) {
log.error(ExceptionUtil.getMessage(e)); // 异常输出语句
e.printStackTrace();
return R.error().code(e.getCode()).message(e.getMsg());
}