引入依赖
pom.xml
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
配置
/resources
logback-spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- 定义日志输出格式,输出路径LOG_PATH-->
<property name="LOG_PATTERN" value="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"/>
<property name="LOG_PATH" value="/logs"/>
<!-- 定义输出到控制台的 appender 本地logger-->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${LOG_PATTERN}</pattern>
</encoder>
</appender>
<!-- 定义输出到文件的 appender-->
<appender name="INFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_PATH}/common-default.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志文件输出的文件名-->
<FileNamePattern>${LOG_HOME}/common-default.%d{yyyy-MM-dd}.log</FileNamePattern>
<!--日志文件保留天数-->
<MaxHistory>3</MaxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>${LOG_PATTERN}</pattern>
</encoder>
<!--日志文件最大的大小 -->
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
<!-- 定义输出到文件的 appender -->
<appender name="ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOG_PATH}/common-error.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志文件输出的文件名-->
<FileNamePattern>${LOG_HOME}/common-error.%d{yyyy-MM-dd}.log</FileNamePattern>
<!--日志文件保留天数-->
<MaxHistory>3</MaxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
<pattern>${LOG_PATTERN}</pattern>
</encoder>
<!--日志文件最大的大小 -->
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
<!-- 定义根日志级别和 appender -->
<Logger name="com.water.disasters.service" level="INFO">
<appender-ref ref="INFO"/>
</Logger>
<Logger name="com.water.disasters.service.aspect" level="ERROR" >
<appender-ref ref="ERROR"/>
</Logger>
<root level="INFO">
<appender-ref ref="CONSOLE" />
</root>
</configuration>
Docker容器配置
/docker-compose.yml
java_backend:
ports: //端口号映射
‘8888:8888’ //线上端口:本地项目配置的端口
volumes: //项目路径映射
“项目绝对地址:/jar包名” //如:"/usr/local/soft/../jar包名:/jar包名"
“日志绝对地址:/logs/” //如:"/usr/local/logs/:/logs/"
切面类
/java/com.oui.risk/aspect
ExceptionHandleAspect.java
@Around("execution(* 路径..*.*(..))")
@Component
@Aspect
public class ExceptionHandleAspect {
public static final Logger logger = LoggerFactory.getLogger(ExceptionHandleAspect.class);
@Around("execution(* com.oui.risk.controller..*.*(..))")
public Object handleExceptions(ProceedingJoinPoint joinPoint) throws Throwable {
//出现异常时记录异常日志
try {
// 执行目标方法
return joinPoint.proceed();
} catch (DemoException demoException){
logger.error("Exception message:", demoException.getMessage());
return CommonResponse.buildErrorResponse(demoException.getCode()
,demoException.getDetail());
} catch (Exception e) {
// 可以在这里记录日志或者进行其他异常处理操作
logger.error("Exception message:", e);
return CommonResponse.buildErrorResponse(e.getMessage());
}
}
}
应用
public class Demo{
//在类里实例化logger对象,传入当前类的类名。
public static final Logger logger = LoggerFactory.getLogger(Demo.class);
public void test(){
//调试时logger.info()可以替代System.out.println()
//代码中每一个输出的日志信息都要明确输出的目的。
//不输出无意义的日志信息
logger.info();
logger.error();
//可以选择抛出异常
//运行异常
throw new RuntimeException(“异常信息”);
//自定义异常类
throw new DemoException(DemoErrorEnum.PARAM_IS_ERROR);
}
}
创建异常类和定义异常枚举类,可以自定义异常,输出异常信息给前端
/enum
DemoErrorEnum.class
public enum DemoErrorEnum{
//相同
PARAM_IS_NULL(1001,"参数为空"),
RESULT_IS_NULL(1002,"查询数据暂时为空"),
PARAM_IS_ERROR(1002,"参数错误"),
DATA_ALREADY_EXIST(1004,"数据已存在"),
//政区
POLITICAL_NOT_EXIST(2001,"政区编码不存在"),
;
private final Integer code;
private final String detail;
DemoErrorEnum(Integer code, String detail) {
this.code = code;
this.detail = detail;
}
public Integer getCode() {
return code;
}
public String getDetail() {
return detail;
}
}
/exception
DemoException.class
public class DemoException extends RuntimeException{
private Integer code;
private String detail;
public DemoException(){
}
public DemoException(String message){
super(message);
}
//传入自定义的异常枚举对象
public DemoException(DemoErrorEnum demoErrorEnum){
this.detail = demoErrorEnum.getDetail();
this.code = demoErrorEnum.getCode();
}
public DemoException(Throwable cause) {
super(cause);
}
public DemoException(String message, Throwable cause) {
super(message, cause);
}
public DemoException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}