<?xml version="1.0" encoding="UTF-8" ?> <configuration> <!--定義日誌文件的存儲地址 勿在 LogBack 的配置中使用相對路徑--> <property name="LOG_HOME" value="${catalina.base}/logs/" /> <!-- 控制檯輸出 --> <appender name="Stdout" class="ch.qos.logback.core.ConsoleAppender"> <!-- 日誌輸出編碼 --> <layout class="ch.qos.logback.classic.PatternLayout"> <!--格式化輸出:%d 表示日期,%thread 表示線程 名,%-5level:級別從左顯示 5 個字符寬度%msg:日誌消息,%n 是換行符--> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n </pattern> </layout> </appender> <!-- 按照天天生成日誌文件 --> <appender name="RollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender"> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!--日誌文件輸出的文件名--> <FileNamePattern>${LOG_HOME}/server.%d{yyyy-MM-dd}.log</FileNa mePattern> <MaxHistory>30</MaxHistory> </rollingPolicy> <layout class="ch.qos.logback.classic.PatternLayout"> <!--格式化輸出:%d 表示日期,%thread 表示線程 名,%-5level:級別從左顯示 5 個字符寬度%msg:日誌消息,%n 是換行符--> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n </pattern> </layout> <!--日誌文件最大的大小--> <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy"> <MaxFileSize>10MB</MaxFileSize> </triggeringPolicy> </appender> <!-- 日誌輸出級別 --> <root level="info"> <appender-ref ref="Stdout" /> <appender-ref ref="RollingFile" /> </root> <!--日誌異步到數據庫 --> <!-- <appender name="DB" class="ch.qos.logback.classic.db.DBAppender"> 日誌異步到數據庫 <connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource"> 鏈接池 <dataSource class="com.mchange.v2.c3p0.ComboPooledDataSource"> <driverClass>com.mysql.jdbc.Driver</driverClass> <url>jdbc:mysql://127.0.0.1:3306/databaseName</url> <user>root</user> <password>root</password> </dataSource> </connectionSource> </appender> --> </configuration>
@ControllerAdvice public class MyControllerAdvice { @ResponseBody @ExceptionHandler(value=java.lang.Exception.class) public Map<String, Object> myException(Exception ex) { Map<String, Object> map = new HashMap<>(); map.put("code", 500); map.put("msg", "出錯了。"); return map; } @ResponseBody @ExceptionHandler(value=java.lang.NullPointerException.c lass) public Map<String, Object> myException2(Exception ex) { Map<String, Object> map = new HashMap<>(); map.put("code", -500); map.put("msg", "空指針異常"); return map; } @ResponseBody @ExceptionHandler(value=com.bjsxt.springboothelloworld.e xception.ApplicationException.class) public Map<String, Object> myException3(Exception ex) { Map<String, Object> map = new HashMap<>(); map.put("code", -800); map.put("msg", ex.getMessage()); return map; } }
@SpringBootApplication @EnableAdminServer public class SpringbootServerApplication { public static void main(String[] args) { SpringApplication.run(SpringbootServerApplication.class, args); } }