init commit
This commit is contained in:
commit
4ffd2436ba
44 files changed
+6584
No files matched your search
@@ -0,0 +1,17 @@
|
||||
package cc.evil.logtest1;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.web.servlet.ServletComponentScan;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
@ServletComponentScan // 启用 @WebFilter 的注解
|
||||
@EnableScheduling // 启用定时任务
|
||||
@SpringBootApplication
|
||||
public class LogTest1Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(LogTest1Application.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package cc.evil.logtest1.aop.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* 一些记录controller日志的配置, 待扩展;
|
||||
*/
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface DefaultControllerLog {
|
||||
/**
|
||||
* 功能描述
|
||||
*/
|
||||
String desc() default "";
|
||||
|
||||
/**
|
||||
* 是否记录请求参数
|
||||
*/
|
||||
boolean recordParams() default false;
|
||||
|
||||
/**
|
||||
* 是否记录响应结果
|
||||
*/
|
||||
boolean recordResult() default true;
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package cc.evil.logtest1.aop.aspcet;
|
||||
|
||||
import cc.evil.logtest1.aop.annotation.DefaultControllerLog;
|
||||
import cc.evil.logtest1.exception.EvilBaseException;
|
||||
import cc.evil.logtest1.log.ControllerLogBO;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.*;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
* Controller的AOP类, 用来统计接口信息;
|
||||
* <p>
|
||||
* 记录的信息包括:
|
||||
* - 自定义描述
|
||||
* - 类名
|
||||
* - 方法名
|
||||
* - 请求uri
|
||||
* - 请求的uid
|
||||
* - 请求响应时间
|
||||
* - 异常信息
|
||||
* - 响应状态码
|
||||
*/
|
||||
@Aspect
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class DefaultControllerLogAspect {
|
||||
// utils
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Around("@annotation(logconfig)")
|
||||
public Object aroundController(ProceedingJoinPoint pjp, DefaultControllerLog logconfig) throws Throwable {
|
||||
// 获取请求上下文
|
||||
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
|
||||
if (attributes == null) {
|
||||
return pjp.proceed();
|
||||
}
|
||||
|
||||
HttpServletRequest request = attributes.getRequest();
|
||||
long startTime = System.currentTimeMillis();
|
||||
|
||||
// 获取方法信息
|
||||
MethodSignature signature = (MethodSignature) pjp.getSignature();
|
||||
Method method = signature.getMethod();
|
||||
String className = pjp.getTarget().getClass().getSimpleName();
|
||||
String methodName = method.getName();
|
||||
|
||||
ControllerLogBO logBo = new ControllerLogBO();
|
||||
logBo.setDesc(logconfig.desc());
|
||||
logBo.setClassName(className);
|
||||
logBo.setMethodName(methodName);
|
||||
logBo.setUri(request.getRequestURI());
|
||||
logBo.setUid(getUid(request));
|
||||
|
||||
Throwable caught = null;
|
||||
try {
|
||||
return pjp.proceed();
|
||||
} catch (Throwable e) {
|
||||
caught = e;
|
||||
throw e;
|
||||
} finally {
|
||||
logBo.setDurationMs(System.currentTimeMillis() - startTime);
|
||||
logBo.setException(caught != null ? caught.getClass().getName() : null);
|
||||
logBo.setStatus(resolveStatus(attributes, caught));
|
||||
|
||||
try {
|
||||
log.info(objectMapper.writeValueAsString(logBo));
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to serialize ControllerLogBO: {}, error message: {}", logBo, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private HttpStatus resolveStatus(ServletRequestAttributes attributes, Throwable e) {
|
||||
if (e != null) {
|
||||
if (e instanceof EvilBaseException) {
|
||||
return ((EvilBaseException) e).getErrorCode().getHttpStatus();
|
||||
}
|
||||
return HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
}
|
||||
|
||||
HttpServletResponse response = attributes.getResponse();
|
||||
if (response != null) {
|
||||
try {
|
||||
return HttpStatus.valueOf(response.getStatus());
|
||||
} catch (Exception ex) {
|
||||
log.warn("Failed to resolve HTTP status from response, error message: {}", ex.getMessage());
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// TODO: 完善获取Uid的逻辑
|
||||
private String getUid(HttpServletRequest request) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package cc.evil.logtest1.config;
|
||||
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.annotation.EnableAsync;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
/**
|
||||
* SpringBoot异步配置类
|
||||
*/
|
||||
@EnableAsync
|
||||
@Configuration
|
||||
public class AsyncConfig {
|
||||
/**
|
||||
* 自定义的异步可追踪日志线程池, 这样异步也能追踪到日志链;
|
||||
* 只需要标记@Async("traceableExecutor")注解就能够使用;
|
||||
*/
|
||||
@Bean("traceableExecutor")
|
||||
public Executor traceableExecutor() {
|
||||
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
|
||||
executor.setCorePoolSize(5); // 基础线程数量
|
||||
executor.setMaxPoolSize(20); // 最大线程数量;
|
||||
executor.setQueueCapacity(100);
|
||||
executor.setThreadNamePrefix("trace-exec-");
|
||||
|
||||
// 包装任务, 传递 MDC
|
||||
executor.setTaskDecorator(runnable -> {
|
||||
// 在提交任务时捕获当前线程的 MDC
|
||||
Map<String, String> contextMap = MDC.getCopyOfContextMap();
|
||||
|
||||
return () -> {
|
||||
try {
|
||||
// 在新线程中恢复 MDC
|
||||
if (contextMap != null) {
|
||||
MDC.setContextMap(contextMap);
|
||||
}
|
||||
runnable.run();
|
||||
} finally {
|
||||
// 清理上下文
|
||||
MDC.clear();
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
executor.initialize();
|
||||
return executor;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package cc.evil.logtest1.config;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class BaseConfig {
|
||||
/**
|
||||
* 创建默认的ObjectMapper Bean, 以便在整个应用中使用同一个实例, 不用反复实例化;
|
||||
*/
|
||||
@Bean
|
||||
public ObjectMapper objectMapper() {
|
||||
return new ObjectMapper();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package cc.evil.logtest1.config;
|
||||
|
||||
import lombok.Getter;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.mail.MailSender;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
import org.springframework.mail.javamail.JavaMailSenderImpl;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 一些邮箱的配置类, 在这里统一管理配置;
|
||||
*/
|
||||
@Configuration
|
||||
public class MailConfig {
|
||||
/**
|
||||
* 邮件服务器配置
|
||||
*/
|
||||
@Value("${log.push.mail.username:}")
|
||||
private String username;
|
||||
|
||||
@Value("${log.push.mail.password:}")
|
||||
private String password;
|
||||
|
||||
@Value("${log.push.mail.host:}")
|
||||
private String host;
|
||||
|
||||
@Value("${log.push.mail.port:}")
|
||||
private int port;
|
||||
|
||||
@Value("${log.push.mail.protocol:smtp}")
|
||||
private String protocol;
|
||||
|
||||
/**
|
||||
* 收发邮箱配置, 默认都为空;
|
||||
*/
|
||||
@Getter
|
||||
@Value("${log.push.mail.from-email:}")
|
||||
private String fromEmail;
|
||||
|
||||
// 列表, 用逗号分隔
|
||||
@Value("${log.push.mail.to-emails:#{new java.util.ArrayList()}}")
|
||||
private List<String> toEmails;
|
||||
|
||||
@Getter
|
||||
private Set<String> toEmailsSet = new HashSet<>();
|
||||
|
||||
/**
|
||||
* MailSender配置;
|
||||
*/
|
||||
@Bean
|
||||
public JavaMailSender getMailSender() {
|
||||
JavaMailSenderImpl sender = new JavaMailSenderImpl();
|
||||
sender.setHost(host);
|
||||
sender.setPort(port);
|
||||
sender.setUsername(username);
|
||||
sender.setPassword(password);
|
||||
sender.setProtocol(protocol);
|
||||
sender.setDefaultEncoding("UTF-8");
|
||||
|
||||
Properties props = new Properties();
|
||||
props.put("mail.smtp.auth", true);
|
||||
props.put("mail.smtp.starttls.enable", true);
|
||||
props.put("mail.smtp.starttls.required", true);
|
||||
props.put("mail.smtp.timeout", 5000);
|
||||
sender.setJavaMailProperties(props);
|
||||
|
||||
toEmailsSet.addAll(toEmails);
|
||||
|
||||
return sender;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加和删除发送邮箱;
|
||||
*/
|
||||
public void addEmail(List<String> toEmails) {
|
||||
this.toEmailsSet.addAll(toEmails);
|
||||
}
|
||||
|
||||
public void removeEmail(String toEmail) {
|
||||
this.toEmailsSet.remove(toEmail);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package cc.evil.logtest1.constants;
|
||||
|
||||
/**
|
||||
* 日志记录的一些常量设置
|
||||
*/
|
||||
public class LogConstants {
|
||||
|
||||
public static final String TRACE_ID_HEADER = "X-Trace-Id";
|
||||
public static final String TRACE_ID_MDC_KEY = "traceId";
|
||||
public static final String SPAN_ID_MDC_KEY = "spanId";
|
||||
|
||||
private LogConstants() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package cc.evil.logtest1.controller;
|
||||
|
||||
import cc.evil.logtest1.aop.annotation.DefaultControllerLog;
|
||||
import cc.evil.logtest1.exception.ClientException;
|
||||
import cc.evil.logtest1.exception.EvilBaseException;
|
||||
import cc.evil.logtest1.exception.EvilErrorCode;
|
||||
import cc.evil.logtest1.exception.InternalServerException;
|
||||
import cc.evil.logtest1.service.TestService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/api/test")
|
||||
public class TestController {
|
||||
// service
|
||||
private final TestService testService;
|
||||
|
||||
@DefaultControllerLog(desc = "获取名字")
|
||||
@GetMapping("/get-name-reverse/{name}")
|
||||
public String getNameReverse(@PathVariable String name) {
|
||||
log.info("getNameReverse called with name: {}", name);
|
||||
String reversedName = testService.reverseStr(name);
|
||||
testService.printStr(reversedName, 50);
|
||||
log.info("Reversed name: {}", reversedName);
|
||||
return reversedName;
|
||||
}
|
||||
|
||||
@GetMapping("/add/{a}/{b}")
|
||||
@DefaultControllerLog(desc = "加法运算")
|
||||
public String add(@PathVariable String a, @PathVariable String b) {
|
||||
try {
|
||||
int numa = 0, numb = 0;
|
||||
try {
|
||||
numa = Integer.parseInt(a);
|
||||
numb = Integer.parseInt(b);
|
||||
} catch (NumberFormatException e) {
|
||||
throw new EvilBaseException(EvilErrorCode.BAD_REQUEST, "参数必须是整数");
|
||||
}
|
||||
return testService.add(numa, numb);
|
||||
} catch (EvilBaseException ebe) {
|
||||
throw ebe;
|
||||
} catch (Exception e) {
|
||||
throw new InternalServerException(EvilErrorCode.UNEXPECTED_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/test-normal-exception")
|
||||
public String testNormalException() {
|
||||
var a = new ClientException(EvilErrorCode.UNAUTHORIZED, "401错误测试");
|
||||
a.setPushLogNow(true);
|
||||
throw a;
|
||||
}
|
||||
|
||||
@GetMapping("/test-normal-exception1")
|
||||
public String testNormalException1() {
|
||||
throw new InternalServerException(EvilErrorCode.INTERNAL_SERVER_ERROR, "500错误测试");
|
||||
}
|
||||
|
||||
@GetMapping("/test-unexpected-exception")
|
||||
public String testUnexpectedException() {
|
||||
throw new RuntimeException("这是一个未预期的异常");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package cc.evil.logtest1.controller.logger;
|
||||
|
||||
import cc.evil.logtest1.exception.ClientException;
|
||||
import cc.evil.logtest1.exception.EvilBaseException;
|
||||
import cc.evil.logtest1.exception.EvilErrorCode;
|
||||
import cc.evil.logtest1.exception.InternalServerException;
|
||||
import cc.evil.logtest1.model.dto.EmailListDTO;
|
||||
import cc.evil.logtest1.model.vo.LogFileNameList;
|
||||
import cc.evil.logtest1.service.log.LogFileService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 实现日志的基本功能:
|
||||
* - 获取日志文件列表, 支持按日期范围过滤;
|
||||
* - 获取日志文件的尾部内容, 支持指定行数;
|
||||
* - 下载日志文件, 支持批量下载并打包成zip;
|
||||
* - 添加和删除发送邮箱;
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/logs")
|
||||
@RequiredArgsConstructor
|
||||
public class LogsController {
|
||||
|
||||
// service
|
||||
private final LogFileService logFileService;
|
||||
|
||||
/**
|
||||
* 日志日期格式
|
||||
*/
|
||||
@Value("${logs.file.date_format:yyyy-MM-dd}")
|
||||
private final String dateFormat = "yyyy-MM-dd";
|
||||
|
||||
private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
|
||||
|
||||
@GetMapping("/files")
|
||||
public LogFileNameList getLogsFiles(@RequestParam(value = "startDate", required = false) String startDate, @RequestParam(value = "endDate", required = false) String endDate) {
|
||||
LocalDate start = null, end = null;
|
||||
try {
|
||||
if (startDate != null && !startDate.isBlank())
|
||||
start = LocalDate.parse(startDate.trim(), formatter);
|
||||
if (endDate != null && !endDate.isBlank())
|
||||
end = LocalDate.parse(endDate.trim(), formatter);
|
||||
if (start != null && end != null && start.isAfter(end))
|
||||
throw new EvilBaseException(EvilErrorCode.TIME_LOGICAL_ERROR);
|
||||
if (end != null && end.isAfter(LocalDate.now()))
|
||||
endDate = LocalDate.now().format(formatter);
|
||||
return logFileService.getLogFiles(start, end);
|
||||
} catch (EvilBaseException ebe) {
|
||||
throw ebe;
|
||||
} catch (DateTimeParseException e) {
|
||||
throw new ClientException(EvilErrorCode.BAD_REQUEST, "日期解析错误");
|
||||
} catch (Exception e) {
|
||||
throw new InternalServerException(EvilErrorCode.UNEXPECTED_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/tail")
|
||||
public List<String> getFileTail(@RequestParam(value = "lines", defaultValue = "200") int lines) {
|
||||
lines = Math.min(lines, 500);
|
||||
try {
|
||||
return logFileService.fileTail(lines);
|
||||
} catch (EvilBaseException ebe) {
|
||||
throw ebe;
|
||||
} catch (Exception e) {
|
||||
throw new InternalServerException(EvilErrorCode.UNEXPECTED_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/download")
|
||||
public void downloadLogs(@RequestBody LogFileNameList logFileNameList, HttpServletResponse response) {
|
||||
if (logFileNameList == null || logFileNameList.getLogFilesByDate() == null || logFileNameList.getLogFilesByDate().isEmpty()) {
|
||||
throw new ClientException(EvilErrorCode.BAD_REQUEST, "下载文件列表不能为空");
|
||||
}
|
||||
|
||||
try {
|
||||
String downloadFileName = "logs-" + LocalDate.now().format(formatter) + ".zip";
|
||||
response.setContentType("application/zip");
|
||||
response.setHeader("Content-Disposition", "attachment; filename=\"" + downloadFileName + "\"");
|
||||
logFileService.writeLogsToZip(logFileNameList, response.getOutputStream());
|
||||
response.flushBuffer();
|
||||
} catch (EvilBaseException ebe) {
|
||||
throw ebe;
|
||||
} catch (IOException e) {
|
||||
throw new InternalServerException(EvilErrorCode.SERVER_FILE_IO_ERROR, "下载日志压缩包失败");
|
||||
} catch (Exception e) {
|
||||
throw new InternalServerException(EvilErrorCode.UNEXPECTED_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/email")
|
||||
public void addEmail(@RequestBody EmailListDTO email) {
|
||||
try {
|
||||
logFileService.addEmails(email.getEmails());
|
||||
} catch (EvilBaseException ebe) {
|
||||
throw ebe;
|
||||
} catch (Exception e) {
|
||||
throw new InternalServerException(EvilErrorCode.UNEXPECTED_ERROR);
|
||||
}
|
||||
}
|
||||
|
||||
@DeleteMapping("/email")
|
||||
public void delEmail(@RequestBody EmailListDTO email) {
|
||||
try {
|
||||
for (var emails : email.getEmails()) {
|
||||
logFileService.removeEmail(emails);
|
||||
}
|
||||
} catch (EvilBaseException ebe) {
|
||||
throw ebe;
|
||||
} catch (Exception e) {
|
||||
throw new InternalServerException(EvilErrorCode.UNEXPECTED_ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package cc.evil.logtest1.exception;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* 客户端异常
|
||||
*/
|
||||
@Getter
|
||||
public class ClientException extends EvilBaseException {
|
||||
private final EvilErrorCode errorCode;
|
||||
private final String customMsg;
|
||||
public ClientException(EvilErrorCode errorCode) {
|
||||
super(errorCode);
|
||||
this.errorCode = errorCode;
|
||||
this.customMsg = null;
|
||||
}
|
||||
|
||||
public ClientException(EvilErrorCode errorCode, String message) {
|
||||
super(errorCode, message);
|
||||
this.errorCode = errorCode;
|
||||
this.customMsg = message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package cc.evil.logtest1.exception;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 基础异常类, 所有自定义异常都应该继承这个类
|
||||
* 应该将错误码的消息传给上层异常, 用来返回给前端, 而CustomMsg是用来记录日志的, 可能包含一些敏感信息, 不应该返回给前端
|
||||
*/
|
||||
public class EvilBaseException extends RuntimeException {
|
||||
@Getter
|
||||
private final EvilErrorCode errorCode;
|
||||
@Getter
|
||||
private final String customMsg;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public boolean pushLogNow = false; // 是否立即推送日志, 而不是等待窗口再推送
|
||||
|
||||
public EvilBaseException(EvilErrorCode errorCode) {
|
||||
super(errorCode.getMessage());
|
||||
this.errorCode = errorCode;
|
||||
this.customMsg = null;
|
||||
}
|
||||
|
||||
public EvilBaseException(EvilErrorCode errorCode, String customMsg) {
|
||||
super(errorCode.getMessage());
|
||||
this.errorCode = errorCode;
|
||||
this.customMsg = customMsg;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package cc.evil.logtest1.exception;
|
||||
|
||||
import lombok.Getter;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
@Getter
|
||||
public enum EvilErrorCode {
|
||||
/**
|
||||
* 4** 错误
|
||||
*/
|
||||
BAD_REQUEST(HttpStatus.BAD_REQUEST, 40001, "请求参数错误"),
|
||||
|
||||
TIME_LOGICAL_ERROR(HttpStatus.BAD_REQUEST, 40002, "时间逻辑错误"),
|
||||
|
||||
UNAUTHORIZED(HttpStatus.UNAUTHORIZED, 40101, "未授权访问"),
|
||||
|
||||
/**
|
||||
* 5** 错误
|
||||
*/
|
||||
UNEXPECTED_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, 50000, "未知错误"),
|
||||
|
||||
INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, 50001, "服务器内部错误"),
|
||||
|
||||
SERVER_FILE_IO_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, 50002, "服务器文件系统错误"),
|
||||
|
||||
INTERNAL_PRECONDITION_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, 50003, "内部参数校验错误")
|
||||
|
||||
|
||||
;
|
||||
|
||||
|
||||
private final HttpStatus httpStatus;
|
||||
private final int businessCode;
|
||||
private final String message;
|
||||
|
||||
EvilErrorCode(HttpStatus httpStatus, int businessCode, String message) {
|
||||
this.httpStatus = httpStatus;
|
||||
this.businessCode = businessCode;
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package cc.evil.logtest1.exception;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* 服务器内部异常
|
||||
*/
|
||||
@Getter
|
||||
public class InternalServerException extends EvilBaseException {
|
||||
private final EvilErrorCode errorCode;
|
||||
private final String customMsg;
|
||||
|
||||
public InternalServerException(EvilErrorCode errorCode) {
|
||||
super(errorCode);
|
||||
this.errorCode = errorCode;
|
||||
this.customMsg = null;
|
||||
}
|
||||
|
||||
public InternalServerException(EvilErrorCode errorCode, String message) {
|
||||
super(errorCode, message);
|
||||
this.errorCode = errorCode;
|
||||
this.customMsg = message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package cc.evil.logtest1.filters;
|
||||
|
||||
import cc.evil.logtest1.constants.LogConstants;
|
||||
import cc.evil.logtest1.utils.TraceContextUtil;
|
||||
import jakarta.servlet.*;
|
||||
import jakarta.servlet.annotation.WebFilter;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.core.annotation.Order;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Order(1)
|
||||
//@Component -> 不需要这个, 这个会和WebFilter冲突, 导致重复注册Bean
|
||||
@WebFilter(urlPatterns = "/*", filterName = "traceIdFilter") // 过滤所有请求
|
||||
public class TraceIdFilter implements Filter {
|
||||
@Override
|
||||
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
|
||||
HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
|
||||
HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
|
||||
System.out.println("TraceIdFilter doFilter: " + httpRequest.getRequestURI());
|
||||
|
||||
try {
|
||||
// ========== 1. 获取或生成 TraceId ==========
|
||||
String traceId = httpRequest.getHeader(LogConstants.TRACE_ID_HEADER);
|
||||
TraceContextUtil.init(traceId);
|
||||
|
||||
// ========== 2. 放入请求属性,方便后续取用 ==========
|
||||
httpRequest.setAttribute(LogConstants.TRACE_ID_HEADER, TraceContextUtil.getTraceId());
|
||||
|
||||
// ========== 3. 设置到响应头 ==========
|
||||
httpResponse.setHeader(LogConstants.TRACE_ID_HEADER, TraceContextUtil.getTraceId());
|
||||
|
||||
// ========== 4. 放行 ==========
|
||||
filterChain.doFilter(servletRequest, servletResponse);
|
||||
|
||||
} finally {
|
||||
// ========== 5. 清理 ==========
|
||||
TraceContextUtil.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package cc.evil.logtest1.handler;
|
||||
|
||||
import cc.evil.logtest1.exception.ClientException;
|
||||
import cc.evil.logtest1.exception.EvilBaseException;
|
||||
import cc.evil.logtest1.exception.EvilErrorCode;
|
||||
import cc.evil.logtest1.exception.InternalServerException;
|
||||
import cc.evil.logtest1.model.vo.EvilResponse;
|
||||
import cc.evil.logtest1.service.log.LogService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.MissingServletRequestParameterException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
|
||||
@Slf4j
|
||||
@RestControllerAdvice(basePackages = "cc.evil.logtest1.controller")
|
||||
@RequiredArgsConstructor
|
||||
public class BusinessControllerExceptionHandler {
|
||||
|
||||
private final LogService logService;
|
||||
|
||||
/**
|
||||
* 处理服务器内部错误异常
|
||||
*/
|
||||
@ExceptionHandler(InternalServerException.class)
|
||||
public ResponseEntity<EvilResponse<Void>> handleInternalServerError(InternalServerException e) {
|
||||
// 推送日志到日志系统
|
||||
logService.pushLogWithDefaultPolicy(e);
|
||||
|
||||
// 将错误返回给前端
|
||||
return ResponseEntity
|
||||
.status(e.getErrorCode().getHttpStatus())
|
||||
.body(EvilResponse.error(e.getErrorCode()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理客户端错误
|
||||
*/
|
||||
@ExceptionHandler(ClientException.class)
|
||||
public ResponseEntity<EvilResponse<Void>> handleClientException(ClientException e) {
|
||||
// 推送日志到日志系统
|
||||
logService.pushLogWithDefaultPolicy(e);
|
||||
|
||||
// 将错误返回给前端
|
||||
return ResponseEntity
|
||||
.status(e.getErrorCode().getHttpStatus())
|
||||
.body(EvilResponse.error(e.getErrorCode()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理泛类
|
||||
*/
|
||||
@ExceptionHandler(EvilBaseException.class)
|
||||
public ResponseEntity<EvilResponse<Void>> handleBaseException(EvilBaseException e) {
|
||||
// 推送日志到日志系统
|
||||
logService.pushLogWithDefaultPolicy(e);
|
||||
|
||||
// 将错误返回给前端
|
||||
return ResponseEntity
|
||||
.status(e.getErrorCode().getHttpStatus())
|
||||
.body(EvilResponse.error(e.getErrorCode()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理 Controller 参数解析错误
|
||||
* 这类错误属于客户端请求不合法, 不应按意料之外异常触发邮件告警
|
||||
*/
|
||||
// @ExceptionHandler({
|
||||
// MethodArgumentTypeMismatchException.class,
|
||||
// MissingServletRequestParameterException.class,
|
||||
// HttpMessageNotReadableException.class,
|
||||
// MethodArgumentNotValidException.class,
|
||||
// BindException.class
|
||||
// })
|
||||
// public ResponseEntity<EvilResponse<Void>> handleControllerBadRequest(Exception e) {
|
||||
// log.warn("Bad request in controller: {}", e.getMessage());
|
||||
// return ResponseEntity
|
||||
// .status(HttpStatus.BAD_REQUEST)
|
||||
// .body(EvilResponse.error(EvilErrorCode.BAD_REQUEST));
|
||||
// }
|
||||
|
||||
/*
|
||||
HttpMessageNotReadableException(JSON 解析失败)→ 返回 400
|
||||
HttpRequestMethodNotSupportedException(方法不支持)→ 返回 405
|
||||
MissingServletRequestParameterException(缺少参数)→ 返回 400
|
||||
NoHandlerFoundException(404)→ 返回 404
|
||||
|
||||
*/
|
||||
|
||||
@ExceptionHandler(HttpMessageNotReadableException.class)
|
||||
public ResponseEntity<EvilResponse<Void>> handleHttpMessageNotReadable(
|
||||
HttpMessageNotReadableException ex) {
|
||||
|
||||
// 可选:记录日志(注意不要记录敏感数据)
|
||||
log.warn("JSON parse error: {}", ex.getMessage());
|
||||
|
||||
// 返回 400 Bad Request + 友好的错误信息
|
||||
return ResponseEntity
|
||||
.status(HttpStatus.BAD_REQUEST)
|
||||
.body(EvilResponse.error(EvilErrorCode.BAD_REQUEST));
|
||||
}
|
||||
|
||||
/**
|
||||
* 未捕获的异常 -> 不应该这样做, 太宽泛了
|
||||
*/
|
||||
// @ExceptionHandler(Exception.class)
|
||||
// public ResponseEntity<EvilResponse<Void>> handleException(Exception e) {
|
||||
// log.error("Unexpected exception caught: ", e);
|
||||
// // 推送日志到日志系统
|
||||
// logService.pushLogWithDefaultPolicy(e);
|
||||
//
|
||||
// // 将错误返回给前端,使用通用的服务器内部错误码
|
||||
// return ResponseEntity
|
||||
// .status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
// .body(EvilResponse.error(EvilErrorCode.INTERNAL_SERVER_ERROR));
|
||||
// }
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package cc.evil.logtest1.log;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ControllerLogBO {
|
||||
private String desc;
|
||||
private String className;
|
||||
private String methodName;
|
||||
private String uri;
|
||||
private String uid;
|
||||
private long durationMs;
|
||||
private HttpStatus status;
|
||||
private String exception;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package cc.evil.logtest1.model.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class EmailListDTO {
|
||||
List<String> emails;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package cc.evil.logtest1.model.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class FileDownloadDTO {
|
||||
List<String> files;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package cc.evil.logtest1.model.vo;
|
||||
|
||||
import cc.evil.logtest1.exception.EvilErrorCode;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public class EvilResponse<T> {
|
||||
private Integer code;
|
||||
private String message;
|
||||
private T data;
|
||||
|
||||
public static <T> EvilResponse<T> success(T data) {
|
||||
return EvilResponse.<T>builder()
|
||||
.code(0)
|
||||
.message("success")
|
||||
.data(data)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static <T> EvilResponse<T> success(T data, String successMsg) {
|
||||
return EvilResponse.<T>builder()
|
||||
.code(0)
|
||||
.message(successMsg)
|
||||
.data(data)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static <T> EvilResponse<T> success() {
|
||||
return success(null);
|
||||
}
|
||||
|
||||
public static <T> EvilResponse<T> error(EvilErrorCode errorCode) {
|
||||
return EvilResponse.<T>builder()
|
||||
.code(errorCode.getBusinessCode())
|
||||
.message(errorCode.getMessage())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package cc.evil.logtest1.model.vo;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class LogFileNameList {
|
||||
Map<String, List<String>> logFilesByDate;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package cc.evil.logtest1.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class TestService {
|
||||
public String reverseStr(String str) {
|
||||
log.info("Start reversing string, str = {}.", str);
|
||||
var res = new StringBuilder(str).reverse().toString();
|
||||
log.info("Finished reversing string, res = {}.", res);
|
||||
return res;
|
||||
}
|
||||
|
||||
public String add(int a, int b) {
|
||||
String res = String.valueOf(a + b);
|
||||
log.info("Finished add, res = {}.", res);
|
||||
return res;
|
||||
}
|
||||
|
||||
@Async("traceableExecutor")
|
||||
public void printStr(String str, int n) {
|
||||
for (int i = 1; i <= n; i++) {
|
||||
log.info("Async print {}: {}", i, str);
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException ignore) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
package cc.evil.logtest1.service.log;
|
||||
|
||||
import cc.evil.logtest1.config.MailConfig;
|
||||
import cc.evil.logtest1.exception.EvilBaseException;
|
||||
import cc.evil.logtest1.exception.EvilErrorCode;
|
||||
import cc.evil.logtest1.exception.InternalServerException;
|
||||
import cc.evil.logtest1.model.vo.LogFileNameList;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class LogFileService {
|
||||
|
||||
// config
|
||||
private final MailConfig mailConfig;
|
||||
|
||||
/**
|
||||
* 日期基准路径
|
||||
*/
|
||||
@Value("${logs.file.base-dir:./logs/}")
|
||||
private String logsFileBaseDir;
|
||||
|
||||
/**
|
||||
* 日志日期格式
|
||||
*/
|
||||
@Value("${logs.file.date_format:yyyy-MM-dd}")
|
||||
private final String dateFormat = "yyyy-MM-dd";
|
||||
private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
|
||||
|
||||
/**
|
||||
* 日志命名格式
|
||||
*/
|
||||
@Value("${logs.file.info_prefix:app-info}")
|
||||
private String infoLogsFileNamePrefix = "app-info";
|
||||
|
||||
/**
|
||||
* 获取时间范围内所有日志文件
|
||||
*/
|
||||
public LogFileNameList getLogFiles(LocalDate startTime, LocalDate endTime) {
|
||||
if (startTime != null && endTime != null && startTime.isAfter(endTime)) {
|
||||
throw new InternalServerException(EvilErrorCode.INTERNAL_PRECONDITION_ERROR, "开始时间不能晚于结束时间");
|
||||
}
|
||||
|
||||
var nw = loadAllFiles(startTime, endTime);
|
||||
return nw != null ? new LogFileNameList(nw) : new LogFileNameList();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取日志文件的尾部内容, 支持指定行数;
|
||||
*/
|
||||
public List<String> fileTail(int lines) {
|
||||
var mp = loadAllFiles(null, null);
|
||||
if (mp == null) return new ArrayList<>();
|
||||
List<String> res = new ArrayList<>();
|
||||
|
||||
List<String> data = loadContentByDate("today", lines, mp);
|
||||
if (data != null) res.addAll(data);
|
||||
|
||||
if (res.size() >= lines) return res;
|
||||
mp.remove("today");
|
||||
|
||||
// 历史日志
|
||||
while (!mp.isEmpty() && res.size() < lines) {
|
||||
String mxDate = "";
|
||||
for (var date : mp.keySet()) {
|
||||
if (mxDate.isBlank() || mxDate.compareTo(date) <= 0) {
|
||||
mxDate = date;
|
||||
}
|
||||
}
|
||||
data = loadContentByDate(mxDate, lines - res.size(), mp);
|
||||
if (data != null) res.addAll(data);
|
||||
mp.remove(mxDate);
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将日志打包压缩
|
||||
*/
|
||||
public void writeLogsToZip(LogFileNameList logFileNameList, OutputStream outputStream) {
|
||||
Path logsBasePath = Paths.get(logsFileBaseDir).toAbsolutePath().normalize();
|
||||
Set<String> zipEntryNames = new HashSet<>();
|
||||
|
||||
try (ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(outputStream, 8192), StandardCharsets.UTF_8)) {
|
||||
for (var entry : logFileNameList.getLogFilesByDate().entrySet()) {
|
||||
String dateKey = normalizeDateKey(entry.getKey());
|
||||
List<String> fileNames = entry.getValue();
|
||||
if (fileNames == null || fileNames.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (String rawFileName : fileNames) {
|
||||
String fileName = normalizeFileName(rawFileName);
|
||||
|
||||
Path targetFilePath = "today".equals(dateKey)
|
||||
? logsBasePath.resolve(fileName)
|
||||
: logsBasePath.resolve(dateKey).resolve(fileName);
|
||||
targetFilePath = targetFilePath.toAbsolutePath().normalize();
|
||||
|
||||
if (!targetFilePath.startsWith(logsBasePath) || !Files.isRegularFile(targetFilePath)) {
|
||||
log.warn("尝试访问非法日志文件: {}", targetFilePath);
|
||||
throw new EvilBaseException(EvilErrorCode.BAD_REQUEST, "日志文件不存在或路径非法: " + fileName);
|
||||
}
|
||||
|
||||
String zipEntryName = dateKey + "/" + fileName;
|
||||
if (!zipEntryNames.add(zipEntryName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
zos.putNextEntry(new ZipEntry(zipEntryName));
|
||||
Files.copy(targetFilePath, zos);
|
||||
zos.closeEntry();
|
||||
}
|
||||
}
|
||||
zos.finish();
|
||||
} catch (IOException e) {
|
||||
throw new InternalServerException(EvilErrorCode.SERVER_FILE_IO_ERROR, "打包日志压缩包失败");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载范围内所有的日志名称
|
||||
*/
|
||||
private Map<String, List<String>> loadAllFiles(LocalDate startTime, LocalDate endTime) {
|
||||
File[] files = new File(logsFileBaseDir).listFiles();
|
||||
if (files == null || files.length == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
LocalDate nowDate = LocalDate.now();
|
||||
|
||||
Map<String, List<String>> mp = new HashMap<>();
|
||||
for (File file : files) {
|
||||
List<String> nw;
|
||||
if (file.isFile()) {
|
||||
if (endTime != null && endTime.isBefore(nowDate)) continue;
|
||||
// 代表当天的日志
|
||||
nw = mp.containsKey("today") ? mp.get("today") : new ArrayList<>();
|
||||
nw.add(file.getName());
|
||||
mp.put("today", nw);
|
||||
} else {
|
||||
LocalDate nwDate = LocalDate.parse(file.getName(), formatter);
|
||||
if (startTime != null && nwDate.isBefore(startTime)) {
|
||||
continue;
|
||||
}
|
||||
if (endTime != null && nwDate.isAfter(endTime)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 递归一层遍历日志;
|
||||
nw = new ArrayList<>();
|
||||
for (File nxt : Objects.requireNonNull(file.listFiles())) {
|
||||
if (nxt.isFile()) {
|
||||
nw.add(nxt.getName());
|
||||
}
|
||||
}
|
||||
mp.put(file.getName(), nw);
|
||||
}
|
||||
}
|
||||
log.info("成功加载所有日志文件名");
|
||||
return mp;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加email
|
||||
*/
|
||||
public void addEmails(List<String> emails) {
|
||||
mailConfig.addEmail(emails);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除email
|
||||
*/
|
||||
public void removeEmail(String email) {
|
||||
mailConfig.removeEmail(email);
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载`dataName`这一天的指定行数的日志;
|
||||
*/
|
||||
private List<String> loadContentByDate(String dateName, int lines, Map<String, List<String>> mp) {
|
||||
if (!mp.containsKey(dateName)) return null;
|
||||
|
||||
List<String> todayList = mp.get(dateName).stream().filter(name -> name.startsWith(infoLogsFileNamePrefix)).sorted().toList().reversed(), res = new ArrayList<>();
|
||||
for (var fileName : todayList) {
|
||||
String filePath;
|
||||
if (dateName.equals("today")) {
|
||||
filePath = String.format("%s/%s", logsFileBaseDir, fileName);
|
||||
} else {
|
||||
filePath = String.format("%s/%s/%s", logsFileBaseDir, dateName, fileName);
|
||||
}
|
||||
|
||||
List<String> fileTailList;
|
||||
try {
|
||||
fileTailList = Files.readAllLines(Paths.get(filePath), StandardCharsets.UTF_8);
|
||||
} catch (IOException e) {
|
||||
throw new InternalServerException(EvilErrorCode.SERVER_FILE_IO_ERROR, "服务器文件系统异常");
|
||||
}
|
||||
|
||||
if (res.size() + fileTailList.size() <= lines) {
|
||||
res.addAll(fileTailList);
|
||||
} else {
|
||||
for (int i = 0; i < fileTailList.size() && res.size() < lines; i++) {
|
||||
res.add(fileTailList.get(i));
|
||||
}
|
||||
}
|
||||
}
|
||||
log.info("成功加载日期{}的日志内容, 行数:{}", dateName, res.size());
|
||||
return res;
|
||||
}
|
||||
|
||||
private String normalizeDateKey(String dateKey) {
|
||||
if (dateKey == null || dateKey.isBlank()) {
|
||||
throw new EvilBaseException(EvilErrorCode.BAD_REQUEST, "日期目录不能为空");
|
||||
}
|
||||
|
||||
String normalizedDate = dateKey.trim();
|
||||
if ("today".equals(normalizedDate)) {
|
||||
return normalizedDate;
|
||||
}
|
||||
|
||||
try {
|
||||
LocalDate.parse(normalizedDate, formatter);
|
||||
return normalizedDate;
|
||||
} catch (Exception e) {
|
||||
throw new EvilBaseException(EvilErrorCode.BAD_REQUEST, "非法日期目录: " + normalizedDate);
|
||||
}
|
||||
}
|
||||
|
||||
private String normalizeFileName(String fileName) {
|
||||
if (fileName == null || fileName.isBlank()) {
|
||||
throw new EvilBaseException(EvilErrorCode.BAD_REQUEST, "日志文件名不能为空");
|
||||
}
|
||||
|
||||
String normalizedFileName = fileName.trim();
|
||||
if (normalizedFileName.contains("..") || normalizedFileName.contains("/") || normalizedFileName.contains("\\")) {
|
||||
throw new EvilBaseException(EvilErrorCode.BAD_REQUEST, "非法日志文件名: " + normalizedFileName);
|
||||
}
|
||||
|
||||
if (!normalizedFileName.matches("[A-Za-z0-9._-]+\\.log")) {
|
||||
throw new EvilBaseException(EvilErrorCode.BAD_REQUEST, "仅允许下载 .log 文件: " + normalizedFileName);
|
||||
}
|
||||
|
||||
return normalizedFileName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package cc.evil.logtest1.service.log;
|
||||
|
||||
import cc.evil.logtest1.exception.EvilBaseException;
|
||||
import cc.evil.logtest1.exception.EvilErrorCode;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class LogPushService {
|
||||
|
||||
// service
|
||||
private final MailPushService mailPushService;
|
||||
|
||||
public void push(EvilBaseException exception, String ruleKey, long occurrenceCount, boolean immediate, String reason, StackTraceElement[] stackTrace) {
|
||||
String msgHeader = String.format("[LogTest1 - logs push] ruleKey=%s", ruleKey);
|
||||
String msgBody = String.format("""
|
||||
Push immediate: %s
|
||||
Rule key: %s
|
||||
Occurrence count: %d
|
||||
Reason: %s
|
||||
Exception type: %s
|
||||
Business code: %s
|
||||
Message: %s
|
||||
Custom message: %s
|
||||
Stack trace: %s
|
||||
""", immediate, ruleKey, occurrenceCount, reason, exception.getClass().getName(), exception.getErrorCode().getBusinessCode(), exception.getMessage(), exception.getCustomMsg(), stackTraceToString(stackTrace));
|
||||
mailPushService.pushToAll(msgHeader, msgBody);
|
||||
}
|
||||
|
||||
private Object stackTraceToString(StackTraceElement[] stackTrace) {
|
||||
if (stackTrace == null) {
|
||||
return "null";
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (StackTraceElement element : stackTrace) {
|
||||
sb.append(element.toString()).append("\n");
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package cc.evil.logtest1.service.log;
|
||||
|
||||
import cc.evil.logtest1.exception.EvilBaseException;
|
||||
import cc.evil.logtest1.exception.InternalServerException;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.converter.StringHttpMessageConverter;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
|
||||
import java.util.concurrent.ConcurrentLinkedDeque;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class LogService {
|
||||
|
||||
private static final long DEFAULT_WINDOW_SIZE = 60_000L;
|
||||
private static final long DEFAULT_MAX_WINDOW_SIZE = 5L;
|
||||
private static final long DEFAULT_WINDOW_RELEASE_TIME = 10 * 60_000L;
|
||||
private static final String BASE_PACKAGE = "cc.evil.logtest1.";
|
||||
|
||||
// Service
|
||||
private final LogPushService logPushService;
|
||||
|
||||
// 多线程安全键值对
|
||||
private final ConcurrentMap<String, FailureWindow> failureWindows = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* 默认推送策略:
|
||||
* 1. 普通异常只有到达一定的阈值, 才会出发推送日志的条件, 以避免过多的日志推送
|
||||
* 2. 被标记了严重的异常会立即推送日志, 不需要等待窗口
|
||||
* 3. 当同一个接口大面积失败的时候, 也会立即推送日志, 不需要等待窗口
|
||||
*/
|
||||
@Async("traceableExecutor")
|
||||
public void pushLogWithDefaultPolicy(EvilBaseException exception) {
|
||||
if (exception == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (shouldPushNow(exception)) {
|
||||
// 立即推送
|
||||
log.info("Push now because setting in exception pushed log for exception: {}, ruleKey: {}.", exception.getClass().getName(), buildRuleKey(exception));
|
||||
logPushService.push(exception, buildRuleKey(exception), 1L, true, "pushLogNow=true", exception.getStackTrace());
|
||||
return;
|
||||
}
|
||||
|
||||
evaluateThresholdPolicy(exception);
|
||||
}
|
||||
|
||||
@Async("traceableExecutor")
|
||||
public void pushLogWithDefaultPolicy(Exception exception) {
|
||||
if (exception == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (exception instanceof EvilBaseException evilBaseException) {
|
||||
pushLogWithDefaultPolicy(evilBaseException);
|
||||
return;
|
||||
}
|
||||
|
||||
// 意料之外的异常立即推送, 并且跟上栈信息, 以便后续排查
|
||||
InternalServerException newException = new InternalServerException(cc.evil.logtest1.exception.EvilErrorCode.INTERNAL_SERVER_ERROR, exception.getMessage());
|
||||
newException.initCause(exception);
|
||||
newException.pushLogNow = true;
|
||||
newException.setStackTrace(exception.getStackTrace());
|
||||
|
||||
log.info("Push now for unexpected error pushed log for exception: {}, ruleKey: {}.", exception.getClass().getName(), buildRuleKey(newException));
|
||||
logPushService.push(newException, buildRuleKey(newException), 1L, true, "unexpected exception", exception.getStackTrace());
|
||||
}
|
||||
|
||||
private void evaluateThresholdPolicy(EvilBaseException exception) {
|
||||
long currentTime = System.currentTimeMillis();
|
||||
String ruleKey = buildRuleKey(exception);
|
||||
FailureWindow window = failureWindows.computeIfAbsent(ruleKey, key -> new FailureWindow(currentTime));
|
||||
|
||||
long cnt = window.push_back(currentTime, DEFAULT_WINDOW_SIZE);
|
||||
|
||||
if (cnt >= DEFAULT_MAX_WINDOW_SIZE) {
|
||||
log.info("Push because threshold reached for exception: {}, ruleKey: {}, cnt: {}.", exception.getClass().getName(), ruleKey, cnt);
|
||||
logPushService.push(exception, ruleKey, cnt, false, "threshold reached", null);
|
||||
window.clear();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 定时任务, 定时清理一部分的队列, 防止内存溢出
|
||||
@Scheduled(fixedDelayString = "${log.policy.window-cleanup-delay-ms:60000}")
|
||||
public void cleanupIdleWindows() {
|
||||
long minTime = System.currentTimeMillis() - DEFAULT_WINDOW_RELEASE_TIME;
|
||||
|
||||
failureWindows.forEach((ruleKey, window) -> {
|
||||
window.release(minTime);
|
||||
if (window.shouldRelease(minTime)) {
|
||||
log.info("Remove idle window for ruleKey: {}, because cleanup schedule.", ruleKey);
|
||||
failureWindows.remove(ruleKey, window);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private boolean shouldPushNow(EvilBaseException exception) {
|
||||
return exception.isPushLogNow();
|
||||
}
|
||||
|
||||
private String buildRuleKey(EvilBaseException exception) {
|
||||
return extractApplicationOrigin(exception);
|
||||
}
|
||||
|
||||
// 提取出问题的类和方法, 作为当前日志的来源, 并且只关注我们自己应用的包路径, 避免被第三方库的异常污染
|
||||
private String extractApplicationOrigin(Throwable throwable) {
|
||||
StackTraceElement[] stackTrace = throwable.getStackTrace();
|
||||
for (StackTraceElement element : stackTrace) {
|
||||
if (element.getClassName().startsWith(BASE_PACKAGE)) {
|
||||
return String.format("%s#%s", element.getClassName(), element.getMethodName());
|
||||
}
|
||||
}
|
||||
|
||||
if (stackTrace.length == 0) {
|
||||
return throwable.getClass().getSimpleName();
|
||||
}
|
||||
|
||||
StackTraceElement fallback = stackTrace[0];
|
||||
return String.format("%s#%s", fallback.getClassName(), fallback.getMethodName());
|
||||
}
|
||||
|
||||
private static final class FailureWindow {
|
||||
private final ConcurrentLinkedDeque<Long> dq = new ConcurrentLinkedDeque<>();
|
||||
private final AtomicInteger cnt = new AtomicInteger();
|
||||
private final AtomicLong lstTime = new AtomicLong();
|
||||
|
||||
private FailureWindow(long windowStartMillis) {
|
||||
lstTime.set(windowStartMillis);
|
||||
}
|
||||
|
||||
private long push_back(long currentTime, long windowSize) {
|
||||
lstTime.set(currentTime);
|
||||
release(currentTime - windowSize);
|
||||
dq.offerLast(currentTime);
|
||||
return cnt.incrementAndGet();
|
||||
}
|
||||
|
||||
// 清理掉过期的记录
|
||||
private void release(long minTime) {
|
||||
// 保证操作原子性, 避免在多线程环境下出现计数不准确的情况
|
||||
while (true) {
|
||||
Long time = dq.pollFirst();
|
||||
if (time == null || time >= minTime) {
|
||||
if (time != null) dq.addFirst(time);
|
||||
break;
|
||||
}
|
||||
cnt.decrementAndGet();
|
||||
}
|
||||
}
|
||||
|
||||
private void clear() {
|
||||
dq.clear();
|
||||
cnt.set(0);
|
||||
}
|
||||
|
||||
private boolean shouldRelease(long minTime) {
|
||||
return dq.isEmpty() || lstTime.get() < minTime;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package cc.evil.logtest1.service.log;
|
||||
|
||||
import cc.evil.logtest1.config.MailConfig;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.mail.MailException;
|
||||
import org.springframework.mail.SimpleMailMessage;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class MailPushService {
|
||||
|
||||
// config
|
||||
private final MailConfig mailConfig;
|
||||
|
||||
// mail sender
|
||||
private final JavaMailSender mailSender;
|
||||
|
||||
public void pushToAll(String header, String msg) {
|
||||
if (mailConfig.getToEmailsSet().isEmpty()) {
|
||||
log.info("No email configured for log pushing, skipping email push.");
|
||||
return;
|
||||
}
|
||||
|
||||
SimpleMailMessage emailMessage = new SimpleMailMessage();
|
||||
emailMessage.setFrom(mailConfig.getFromEmail());
|
||||
emailMessage.setSubject(header);
|
||||
emailMessage.setText(msg);
|
||||
for (String toEmail : mailConfig.getToEmailsSet()) {
|
||||
emailMessage.setTo(toEmail);
|
||||
try {
|
||||
mailSender.send(emailMessage);
|
||||
log.info("Successfully sent log email to {}.", toEmail);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to send log email to {}.", toEmail, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package cc.evil.logtest1.utils;
|
||||
|
||||
import cc.evil.logtest1.constants.LogConstants;
|
||||
import org.slf4j.MDC;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class TraceContextUtil {
|
||||
|
||||
/**
|
||||
* 生成 TraceId(32位,无横线的UUID)
|
||||
*/
|
||||
public static String generateTraceId() {
|
||||
return UUID.randomUUID().toString().replace("-", "");
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成 SpanId
|
||||
*/
|
||||
public static String generateSpanId() {
|
||||
return UUID.randomUUID().toString().replace("-", "").substring(0, 16);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置 TraceId 到 MDC
|
||||
*/
|
||||
public static void setTraceId(String traceId) {
|
||||
MDC.put(LogConstants.TRACE_ID_MDC_KEY, traceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置 SpanId 到 MDC
|
||||
*/
|
||||
public static void setSpanId(String spanId) {
|
||||
MDC.put(LogConstants.SPAN_ID_MDC_KEY, spanId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 MDC 获取 TraceId
|
||||
*/
|
||||
public static String getTraceId() {
|
||||
return MDC.get(LogConstants.TRACE_ID_MDC_KEY);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 MDC 获取 SpanId
|
||||
*/
|
||||
public static String getSpanId() {
|
||||
return MDC.get(LogConstants.SPAN_ID_MDC_KEY);
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化(如果没有则生成)
|
||||
*/
|
||||
public static void init(String traceId) {
|
||||
if (traceId == null || traceId.isBlank()) {
|
||||
traceId = generateTraceId();
|
||||
}
|
||||
setTraceId(traceId);
|
||||
setSpanId(generateSpanId());
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理,防止内存泄漏
|
||||
*/
|
||||
public static void clear() {
|
||||
MDC.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
spring:
|
||||
application:
|
||||
name: LogTest1
|
||||
profiles:
|
||||
active: dev
|
||||
|
||||
log:
|
||||
push:
|
||||
mail:
|
||||
username: ${MAIL_USERNAME:}
|
||||
password: ${MAIL_PASSWORD:}
|
||||
host: smtp.qq.com
|
||||
port: 587
|
||||
protocol: smtp
|
||||
from-email: ${MAIL_FROM_EMAIL:}
|
||||
to-emails: ${MAIL_TO_EMAILS:}
|
||||
@@ -0,0 +1,116 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<!-- 1. 定义变量-->
|
||||
<property name="LOG_PATH" value="logs/" /> <!-- 日志文件根目录 -->
|
||||
<property name="LOG_NAME" value="app" /> <!-- 日志基础名称 -->
|
||||
|
||||
<!-- =================== 异步通用配置 =================== -->
|
||||
|
||||
<!-- 常规日志, 输出INFO及以上 -->
|
||||
<appender name="FILE_INFO" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${LOG_PATH}/${LOG_NAME}-info.log</file>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
|
||||
<fileNamePattern>${LOG_PATH}/%d{yyyy-MM-dd}/${LOG_NAME}-info.%i.log</fileNamePattern>
|
||||
<maxFileSize>10MB</maxFileSize>
|
||||
<!-- 最多保留7天 -->
|
||||
<maxHistory>7</maxHistory>
|
||||
<totalSizeCap>5GB</totalSizeCap>
|
||||
</rollingPolicy>
|
||||
<encoder>
|
||||
<pattern>
|
||||
{"time":"%d{yyyy-MM-dd HH:mm:ss.SSS}","level":"%level","traceId":"%X{traceId}","uid":"%X{uid}","thread":"%thread","logger":"%logger","msg":%msg,"exception":"%ex"}%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
|
||||
<level>INFO</level>
|
||||
</filter>
|
||||
</appender>
|
||||
|
||||
<!-- 错误日志, 输出WARN和ERROR -->
|
||||
<appender name="FILE_ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${LOG_PATH}/${LOG_NAME}-error.log</file>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
|
||||
<fileNamePattern>${LOG_PATH}/%d{yyyy-MM-dd}/${LOG_NAME}-error.%i.log</fileNamePattern>
|
||||
<maxFileSize>10MB</maxFileSize>
|
||||
<!-- 最多保留15天 -->
|
||||
<maxHistory>15</maxHistory>
|
||||
<totalSizeCap>3GB</totalSizeCap>
|
||||
</rollingPolicy>
|
||||
<encoder>
|
||||
<pattern>
|
||||
{"time":"%d{yyyy-MM-dd HH:mm:ss.SSS}","level":"%level","traceId":"%X{traceId}","uid":"%X{uid}","thread":"%thread","logger":"%logger","msg":%msg,"exception":"%ex"}%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
|
||||
<level>WARN</level>
|
||||
</filter>
|
||||
</appender>
|
||||
|
||||
<!-- 审计日志 -->
|
||||
<appender name="FILE_AUDIT" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${LOG_PATH}/${LOG_NAME}-audit.log</file>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
|
||||
<fileNamePattern>${LOG_PATH}/%d{yyyy-MM-dd}/${LOG_NAME}-audit.%i.log</fileNamePattern>
|
||||
<maxFileSize>10MB</maxFileSize>
|
||||
<!-- 最多保留30天 -->
|
||||
<maxHistory>30</maxHistory>
|
||||
<totalSizeCap>10GB</totalSizeCap>
|
||||
</rollingPolicy>
|
||||
<encoder>
|
||||
<pattern>
|
||||
{"time":"%d{yyyy-MM-dd HH:mm:ss.SSS}","level":"%level","traceId":"%X{traceId}","uid":"%X{uid}","thread":"%thread","logger":"%logger","msg":%msg,"exception":"%ex"}%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
<filter class="ch.qos.logback.classic.filter.LevelFilter">
|
||||
<level>INFO</level>
|
||||
<onMatch>ACCEPT</onMatch>
|
||||
<onMismatch>DENY</onMismatch>
|
||||
</filter>
|
||||
</appender>
|
||||
|
||||
<!-- 彩色输出到控制台 -->
|
||||
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>
|
||||
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] [%X{traceId}] %highlight(%-5level) %logger{50} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<!-- =================== 异步包装 =================== -->
|
||||
<appender name="ASYNC_INFO" class="ch.qos.logback.classic.AsyncAppender">
|
||||
<queueSize>1024</queueSize>
|
||||
<!-- 队列满时丢弃 TRACE/DEBUG/INFO,保留 WARN和ERROR -->
|
||||
<discardingThreshold>20</discardingThreshold>
|
||||
<neverBlock>true</neverBlock>
|
||||
<appender-ref ref="FILE_INFO"/>
|
||||
</appender>
|
||||
|
||||
<appender name="ASYNC_ERROR" class="ch.qos.logback.classic.AsyncAppender">
|
||||
<queueSize>512</queueSize>
|
||||
<!-- 错误日志绝对不能丢失, 因此不允许丢弃并关闭 neverBlock 让其阻塞等待 -->
|
||||
<discardingThreshold>0</discardingThreshold>
|
||||
<neverBlock>false</neverBlock>
|
||||
<appender-ref ref="FILE_ERROR"/>
|
||||
</appender>
|
||||
|
||||
<appender name="ASYNC_AUDIT" class="ch.qos.logback.classic.AsyncAppender">
|
||||
<queueSize>256</queueSize>
|
||||
<discardingThreshold>0</discardingThreshold>
|
||||
<neverBlock>false</neverBlock>
|
||||
<appender-ref ref="FILE_AUDIT"/>
|
||||
</appender>
|
||||
|
||||
<!-- =================== 日志路由 =================== -->
|
||||
<root level="INFO">
|
||||
<appender-ref ref="CONSOLE" />
|
||||
<appender-ref ref="ASYNC_INFO" />
|
||||
<appender-ref ref="ASYNC_ERROR" />
|
||||
</root>
|
||||
|
||||
<!-- 防止审计日志穿透到root再次输出 -->
|
||||
<logger name="AuditLogger" level="INFO" additivity="false">
|
||||
<appender-ref ref="CONSOLE" />
|
||||
<appender-ref ref="ASYNC_AUDIT" />
|
||||
</logger>
|
||||
</configuration>
|
||||
@@ -0,0 +1,25 @@
|
||||
package cc.evil.logtest1;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.mail.SimpleMailMessage;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
|
||||
@SpringBootTest
|
||||
class LogTest1ApplicationTests {
|
||||
@Autowired
|
||||
private JavaMailSender mailSender;
|
||||
|
||||
@Test
|
||||
void testMail() {
|
||||
SimpleMailMessage msg = new SimpleMailMessage();
|
||||
msg.setFrom("2207086349@qq.com");
|
||||
msg.setTo("2207086349@qq.com");
|
||||
// msg.setTo("3515694291@qq.com");
|
||||
msg.setSubject("主题:简单邮件");
|
||||
msg.setText("测试邮件内容");
|
||||
mailSender.send(msg);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user