springboot+mybatis-plus统一日志处理
1、
<?xml version="1.0" encoding="UTF-8"?> <configuration scan="true" scanPeriod="10 seconds"> <!-- 日志级别从低到高分为TRACE < DEBUG < INFO < WARN < ERROR < FATAL,如果设置为WARN,则低于WARN的信息都不会输出 --> <!-- scan:当此属性设置为true时,配置文件如果发生改变,将会被重新加载,默认值为true --> <!-- scanPeriod:设置监测配置文件是否有修改的时间间隔,如果没有给出时间单位,默认单位是毫秒。当scan为true时,此属性生效。默认的时间间隔为1分钟。 --> <!-- debug:当此属性设置为true时,将打印出logback内部日志信息,实时查看logback运行状态。默认值为false。 --> <contextName>logback</contextName> <!-- name的值是变量的名称,value的值时变量定义的值。通过定义的值会被插入到logger上下文中。定义变量后,可以使“${}”来使用变量。 --> <property name="log.path" value="D:/log/edu" /> <!--控制台日志格式:彩色日志--> <!-- magenta:洋红 --> <!-- boldMagenta:粗红--> <!-- cyan:青色 --> <!-- white:白色 --> <!-- magenta:洋红 --> <property name="CONSOLE_LOG_PATTERN" value="%yellow(%date{yyyy-MM-dd HH:mm:ss}) |%highlight(%-5level) |%blue(%thread) |%blue(%file:%line) |%green(%logger) |%cyan(%msg%n)"/> <!--文件日志格式--> <property name="FILE_LOG_PATTERN" value="%date{yyyy-MM-dd HH:mm:ss} |%-5level |%thread |%file:%line |%logger |%msg%n" /> <!--编码--> <property name="ENCODING" value="UTF-8" /> <!--输出到控制台--> <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> <!--日志级别--> <level>DEBUG</level> </filter> <encoder> <!--日志格式--> <Pattern>${CONSOLE_LOG_PATTERN}</Pattern> <!--日志字符集--> <charset>${ENCODING}</charset> </encoder> </appender> <!--输出到文件--> <appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!--日志过滤器:此日志文件只记录INFO级别的--> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>INFO</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> <!-- 正在记录的日志文件的路径及文件名 --> <file>${log.path}/log_info.log</file> <encoder> <pattern>${FILE_LOG_PATTERN}</pattern> <charset>${ENCODING}</charset> </encoder> <!-- 日志记录器的滚动策略,按日期,按大小记录 --> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- 每天日志归档路径以及格式 --> <fileNamePattern>${log.path}/info/log-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>500MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> <!--日志文件保留天数--> <maxHistory>15</maxHistory> </rollingPolicy> </appender> <appender name="WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!-- 日志过滤器:此日志文件只记录WARN级别的 --> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>WARN</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> <!-- 正在记录的日志文件的路径及文件名 --> <file>${log.path}/log_warn.log</file> <encoder> <pattern>${FILE_LOG_PATTERN}</pattern> <charset>${ENCODING}</charset> <!-- 此处设置字符集 --> </encoder> <!-- 日志记录器的滚动策略,按日期,按大小记录 --> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${log.path}/warn/log-warn-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>100MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> <!--日志文件保留天数--> <maxHistory>15</maxHistory> </rollingPolicy> </appender> <appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!-- 日志过滤器:此日志文件只记录ERROR级别的 --> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>ERROR</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> <!-- 正在记录的日志文件的路径及文件名 --> <file>${log.path}/log_error.log</file> <encoder> <pattern>${FILE_LOG_PATTERN}</pattern> <charset>${ENCODING}</charset> <!-- 此处设置字符集 --> </encoder> <!-- 日志记录器的滚动策略,按日期,按大小记录 --> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${log.path}/error/log-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>100MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> <!--日志文件保留天数--> <maxHistory>15</maxHistory> </rollingPolicy> </appender> <!--开发环境--> <springProfile name="dev"> <!--可以灵活设置此处,从而控制日志的输出--> <root level="INFO"> <appender-ref ref="CONSOLE" /> <appender-ref ref="INFO_FILE" /> <appender-ref ref="WARN_FILE" /> <appender-ref ref="ERROR_FILE" /> </root> </springProfile> <!--生产环境--> <springProfile name="pro"> <root level="ERROR"> <appender-ref ref="ERROR_FILE" /> </root> </springProfile> </configuration>
2、ExceptionUtils工具类
调用 log.error(ExceptionUtil.getMessage(e));
package com.stu.service.base.utils; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; /****************************** * 用途说明: * 作者姓名: Administrator * 创建时间: 2022-04-18 22:26 ******************************/ public class ExceptionUtils { /*********************************** * 用途说明: * 返回值说明: java.lang.String ***********************************/ public static String getMessage(Exception e) { StringWriter sw = null; PrintWriter pw = null; try { sw = new StringWriter(); pw = new PrintWriter(sw); // 将出错的栈信息输出到printWriter中 e.printStackTrace(pw); pw.flush(); sw.flush(); } finally { if (sw != null) { try { sw.close(); } catch (IOException e1) { e1.printStackTrace(); } } if (pw != null) { pw.close(); } } return sw.toString(); } }
3、全局异常
类上添加注解
@Slf4j
异常输出语句
log.error(e.getMessage());
package com.stu.servicebase.handler; import com.stu.service.base.result.R; import com.stu.service.base.utils.ExceptionUtils; import com.stu.servicebase.exception.CustomException; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; /****************************** * 用途说明:统一异常处理 * 作者姓名: Administrator * 创建时间: 2022-04-17 23:32 ******************************/ @Slf4j @ControllerAdvice public class GlobalExceptionHandler { /*********************************** * 用途说明:自定义异常 * 返回值说明: com.stu.service.base.result.R ***********************************/ @ExceptionHandler(CustomException.class) @ResponseBody public R customException(CustomException e){ // e.printStackTrace(); // log.error(e.getMessage()); log.error(ExceptionUtils.getMessage(e)); return R.error().message(e.getMessage()).code(e.getCode()); } /*********************************** * 用途说明:数字异常 * 返回值说明: com.stu.service.base.result.R ***********************************/ @ExceptionHandler(ArithmeticException.class) @ResponseBody public R arithmeticException(Exception e){ log.error(ExceptionUtils.getMessage(e)); return R.error().message(e.getMessage()); } /*********************************** * 用途说明:全局异常 * 返回值说明: com.stu.service.base.result.R ***********************************/ @ExceptionHandler(Exception.class) @ResponseBody public R error(Exception e){ log.error(ExceptionUtils.getMessage(e)); return R.error().message(e.getMessage()); } }
4、自定义异常
package com.stu.servicebase.exception; import com.stu.service.base.result.ResultCodeEnum; import lombok.Data; /****************************** * 用途说明:自定义异常 * 作者姓名: Administrator * 创建时间: 2022-04-18 0:00 ******************************/ @Data public class CustomException extends RuntimeException{ private Integer code; public CustomException(ResultCodeEnum resultCodeEnum){ super(resultCodeEnum.getMessage()); //this.message = resultCodeEnum.getMessage(); this.code = resultCodeEnum.getCode(); } }
5、log文件(error.log为例)
log_error.log文件
2022-04-18 22:22:23 |ERROR |http-nio-9110-exec-9 |GlobalExceptionHandler.java:28 |com.stu.servicebase.handler.GlobalExceptionHandler |除零错误 2022-04-18 22:31:42 |ERROR |http-nio-9110-exec-1 |GlobalExceptionHandler.java:30 |com.stu.servicebase.handler.GlobalExceptionHandler |CustomException(code=29001) at com.stu.service.edu.controller.TeacherController.deleteTeacher(TeacherController.java:42) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) at org.springframework.web.servlet.FrameworkServlet.doDelete(FrameworkServlet.java:931) at javax.servlet.http.HttpServlet.service(HttpServlet.java:666) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:744)