SpringBoot日志 日志以日期和大小分文件存储
springBoot如何输出日志默认是全部都输出到一个文件里了。这样的话文件会越来越大,可能有几个G或者几十G,甚至更大,需要出库日志是比较麻烦。
1.依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
配置文件
logging:
config: classpath:logback-spring.xml
xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- %m输出的信息,%p日志级别,%t线程名,%d日期,%c类的全名,%i索引【从数字0开始递增】,,, -->
<!-- appender是configuration的子节点,是负责写日志的组件。 -->
<!-- ConsoleAppender:把日志输出到控制台 -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d %p (%file:%line\)- %m%n</pattern>
<!-- 控制台也要使用UTF-8,不要使用GBK,否则会中文乱码 -->
<charset>UTF-8</charset>
</encoder>
</appender>
<!-- RollingFileAppender:滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件 -->
<!-- 以下的大概意思是:1.先按日期存日志,日期变了,将前一天的日志文件名重命名为XXX%日期%索引,新的日志仍然是sys.log -->
<!-- 2.如果日期没有发生变化,但是当前日志的文件大小超过1KB时,对当前日志进行分割 重命名-->
<appender name="syslog"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>D:/home/lideru/log/bangke/credit.log</File>
<!-- rollingPolicy:当发生滚动时,决定 RollingFileAppender 的行为,涉及文件移动和重命名。 -->
<!-- TimeBasedRollingPolicy: 最常用的滚动策略,它根据时间来制定滚动策略,既负责滚动也负责出发滚动 -->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 活动文件的名字会根据fileNamePattern的值,每隔一段时间改变一次 -->
<!-- 文件名 -->
<fileNamePattern>D:/home/lideru/log/bangke/%d/credit.%d.%i.log</fileNamePattern>
<!-- 每产生一个日志文件,该日志文件的保存期限为30天 -->
<maxHistory>360</maxHistory>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<!-- maxFileSize:这是活动文件的大小,默认值是10MB,本篇设置为1KB,只是为了演示 -->
<maxFileSize>100KB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder>
<!-- pattern节点,用来设置日志的输入格式 -->
<pattern>
%d %p (%file:%line\)- %m%n
</pattern>
<!-- 记录日志的编码 -->
<charset>UTF-8</charset> <!-- 此处设置字符集 -->
</encoder>
</appender>
<!-- 控制台输出日志级别 -->
<root level="info">
<appender-ref ref="STDOUT"/>
</root>
<!-- 指定项目中某个包,当有日志操作行为时的日志记录级别 -->
<!-- com.lideru为根包,也就是只要是发生在这个根包下面的所有日志操作行为的权限都是DEBUG -->
<!-- 级别依次为【从高到低】:FATAL > ERROR > WARN > INFO > DEBUG > TRACE -->
<logger name="com.lideru" level="DEBUG">
<appender-ref ref="syslog"/>
</logger>
<!--<logger level="DEBUG">-->
<!--<appender-ref ref="syslog"/>-->
<!--</logger>-->
</configuration>
异常拦截
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
@ControllerAdvice
@Component
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(value = Exception.class)
@ResponseBody
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseEntity<String> globalExceptionHandle(Exception e) {
log.error(getExceptionInfo(e));
return new ResponseEntity<>(500, "error", e.getMessage());
}
private static String getExceptionInfo(Exception ex) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
PrintStream printStream = new PrintStream(out);
ex.printStackTrace(printStream);
String rs = new String(out.toByteArray());
try {
printStream.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return rs;
}
}
public class ResponseEntity<T> {
private int code;
private String message;
private T result;
public ResponseEntity(int code, String message, T result) {
this.code = code;
this.message = message;
this.result = result;
}
public ResponseEntity(String message, T result) {
this.code = 200;
this.message = message;
this.result = result;
}
public ResponseEntity(T result) {
this.code = 200;
this.message = "success";
this.result = result;
}
public ResponseEntity() {
this.code = 200;
this.message = "success";
}
public ResponseEntity(Integer code, String msg) {
this.code = code;
this.message = msg;
this.result = null;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getResult() {
return result;
}
public void setResult(T result) {
this.result = result;
}
@Override
public String toString() {
return "ResponseEntity{" +
"code=" + code +
", message='" + message + '\'' +
", result=" + result +
'}';
}
}
控制层
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController()
@Slf4j
public class TestContoller {
@RequestMapping("/test")
public void test() throws InterruptedException {
int i = 1;
while (true) {
log.info("************************ ---->" + i + " <---- ************************ ");
log.error("************************ ---->" + i + " <---- ************************ ");
System.out.println("llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll");
i++;
i %= 10000;
Thread.sleep(100);
}
}
@RequestMapping(value = "testException")
public Object testException() {
int j =1/0;
return 66;
}
}
访问 http://127.0.0.1:8080/testException ,看看D盘;
访问 http://127.0.0.1:8080/test ,看看D盘;
参考了这位前辈 https://blog.csdn.net/Small_Mouse0/article/details/79112227?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522167817160416800182718583%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=167817160416800182718583&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allfirst_rank_ecpm_v1~rank_v31_ecpm-6-79112227-null-null.142v73insert_down4,201v4add_ask,239v2insert_chatgpt&utm_term=springboot%20%E6%97%A5%E5%BF%97%20%E5%88%86%E6%97%A5%E6%9C%9F%20%E4%BF%9D%E5%AD%98&spm=1018.2226.3001.4187