Preface: Now is the era of the anterior and posterior end separation. At present, the transmission format of most data in front and back end development is JSON, so defining a unified and standardized data format is very conducive to the interaction of front and back end and THE display of UI.
1. Unified result return
1.1 What Data is Required for Unified Results?
The following data is often required:
- Return status code
- Return information
- The request status
- The request data
For this, we encapsulate our own return result class!
The code is as follows:
@data public class R {@apiModelProperty (value = "") private Boolean success; @data public class R {@apiModelProperty (value =" ") private Boolean success; @apiModelProperty (value = "return code ") private Integer Code; @apiModelProperty (value = "return message ") private String message; @apiModelProperty (value = "return data ") private Map<String, Object> data = new HashMap<String, Object>(); Public static R ok(){R R = new R();} public static R ok(){R R = new R(); r.setSuccess(true); r.setCode(ResultCode.SUCCESS); R.setmessage (" Operation succeeded "); return r; } public static R error(){ R r = new R(); r.setSuccess(false); r.setCode(ResultCode.ERROR); R.setmessage (" operation failed "); return r; } public R success(Boolean success){ this.setSuccess(success); return this; } public R message(String message){ this.setMessage(message); return this; } public R code(Integer code){ this.setCode(code); return this; } public R data(String key,Object value){ this.data.put(key,value); return this; } public R data(Map<String,Object> map){ this.setData(map); return this; }}Copy the code
A few details:
- The front end receives Json data, and we use Map structure to store data, which is easier to transform and can store more data.
- Using chained programming, where the results of methods are returned to the caller, can be more elegant and simple.
1.2 We need to define some status codes ourselves, I use the interface here to define the demo
public interface ResultCode { Integer SUCCESS = 20000; // Request success Integer ERROR = 20001; // Request failed}Copy the code
1.3 Return at the control layer
Unified exception handling
There is another situation when using uniform return results. Due to the exception of the program, it cannot run to the result returned here, so we need to define a uniform global exception to catch this information and return it to the control layer as a result.
The core annotation @ControllerAdvice
Catch the specified exception: @ExceptionHandler(***.class)
2.1 Customize a global exception handling class using the @ControllerAdvice annotation
@controllerAdvice //************ important ********* public Class GlobalExceptionHandler {// Must @ExceptionHandler(except.class) @responseBody // In order to return data public R error(Exception e){e.printStackTrace(); Return r.ror ().message(" global exception method executed...") ); } / / special exception handling (according to add multiple different types of exceptions) @ ExceptionHandler (ArithmeticException. Class) @ ResponseBody public R error (ArithmeticException e){ e.printStackTrace(); log.error(ExceptionUtil.getMessage(e)); Return r.ror ().message(" arithmetic exception method executed....") ); } // Custom exception handling, @ExceptionHandler(myExcept.class) @responseBody public R error(MyException E){e.printStackTrace(); log.error(ExceptionUtil.getMessage(e)); return R.error().code(e.getCode()).message(e.getMsg()); }}Copy the code
When we test, the program will execute to the corresponding method if an exception occurs, so as to return a friendly unified format of exception information to the front end for operation!
3. Log processing
Logs are recorded in the following levels: OFF, FATAL, ERROR, WARN, INFO, DEBUG, and ALL By default, Only INFO or higher log levels are printed from the Console by Spring Boot. You can set the log level in the configuration file
Logging. Level. Root =WARN note: This mode will only print logs on the consoleCopy the code
3.1 Logback logging
Springboot internally uses logBack logging as the framework for its logging implementation.
3.1.1 Using logBack Logs
- Delete the log configuration in Application.properties
- Install the idea color log plug-in grep-console
- Create logback-spring.xml in resources
The configuration is as follows:
<?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="F:/log" />
<!-- 彩色日志 -->
<!-- 配置格式变量:CONSOLE_LOG_PATTERN 彩色日志格式 -->
<!-- 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)"/>
<!--输出到控制台-->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<!--此日志appender是为开发使用,只配置最底级别,控制台输出的日志级别是大于或等于此级别的日志信息-->
<!-- 例如:如果此处配置了INFO级别,则后面其他位置即使配置了DEBUG级别的日志,也不会被输出 -->
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>INFO</level>
</filter>
<encoder>
<Pattern>${CONSOLE_LOG_PATTERN}</Pattern>
<!-- 设置字符集 -->
<charset>UTF-8</charset>
</encoder>
</appender>
<!--输出到文件-->
<!-- 时间滚动输出 level为 INFO 日志 -->
<appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_info.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</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>100MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<!--日志文件保留天数-->
<maxHistory>15</maxHistory>
</rollingPolicy>
<!-- 此日志文件只记录info级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 WARN 日志 -->
<appender name="WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_warn.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</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>
<!-- 此日志文件只记录warn级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>warn</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!-- 时间滚动输出 level为 ERROR 日志 -->
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 正在记录的日志文件的路径及文件名 -->
<file>${log.path}/log_error.log</file>
<!--日志文件输出格式-->
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
<charset>UTF-8</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>
<!-- 此日志文件只记录ERROR级别的 -->
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>ERROR</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!--
<logger>用来设置某一个包或者具体的某一个类的日志打印级别、以及指定<appender>。
<logger>仅有一个name属性,
一个可选的level和一个可选的addtivity属性。
name:用来指定受此logger约束的某一个包或者具体的某一个类。
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,
如果未设置此属性,那么当前logger将会继承上级的级别。
-->
<!--
使用mybatis的时候,sql语句是debug下才会打印,而这里我们只配置了info,所以想要查看sql语句的话,有以下两种操作:
第一种把<root level="INFO">改成<root level="DEBUG">这样就会打印sql,不过这样日志那边会出现很多其他消息
第二种就是单独给mapper下目录配置DEBUG模式,代码如下,这样配置sql语句会打印,其他还是正常DEBUG级别:
-->
<!--开发环境:打印控制台-->
<springProfile name="dev">
<!--可以输出项目中的debug日志,包括mybatis的sql日志-->
<logger name="com.guli" level="INFO" />
<!--
root节点是必选节点,用来指定最基础的日志输出级别,只有一个level属性
level:用来设置打印级别,大小写无关:TRACE, DEBUG, INFO, WARN, ERROR, ALL 和 OFF,默认是DEBUG
可以包含零个或多个appender元素。
-->
<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="INFO">
<appender-ref ref="CONSOLE" />
<appender-ref ref="DEBUG_FILE" />
<appender-ref ref="INFO_FILE" />
<appender-ref ref="ERROR_FILE" />
<appender-ref ref="WARN_FILE" />
</root>
</springProfile>
</configuration>
Copy the code
3.1.2 Outputting Error Logs to A File
- Add annotations to the global exception handling class
@Slf4j
Copy the code
- Exception output statement
log.error(e.getMessage());
Copy the code
- Define a utility class (used to output exception information to a disk file)
public class ExceptionUtil { public static String getMessage(Exception e) { StringWriter sw = null; PrintWriter pw = null; try { sw = new StringWriter(); pw = new PrintWriter(sw); PrintWriter e.prinintStackTrace (pw); // printWriter e.prinintStackTrace (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(); }}Copy the code
- Call it in the defined global exception class (that is, the class annotated with @ControllerAdvice)
log.error(ExceptionUtil.getMessage(e));
Copy the code
Refer to the following article: juejin.cn/post/684490… Unified Exception Handling blog.csdn.net/Mr_xiaobaic… In addition, the unified results are returned by referring to the lecture content of the teachers of Shangsilicon Valley Valley College.