我的springboot项目中想要异步打印日志到文件,对 logback 做了如下配置
<!-- 异步日志 -->
<appender name="testAsyncAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${log.path}/asyncLog.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${log.path}/asyncLog.%d{yyyy-MM-dd}.log</FileNamePattern>
<MaxHistory>30</MaxHistory>
<totalSizeCap>1GB</totalSizeCap>
</rollingPolicy>
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger{50} - [%thread] - %msg%n</pattern>
</encoder>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>
<appender name="asyncAppender" class="ch.qos.logback.classic.AsyncAppender">
<appender-ref ref="testAsyncAppender" />
<queueSize>10000</queueSize>
<discardingThreshold>0</discardingThreshold>
<neverBlock>true</neverBlock>
</appender>
<logger name="asyncLog" level="info" additivity="false">
<appender-ref ref="asyncAppender" />
</logger>
java的controller中使用下面代码打印日志
private static final Logger asyncLog = LoggerFactory.getLogger("asyncLog");
public JsonResult selectByPrimaryKey(@PathVariable Integer pk){
asyncLog.info("异步日志查询之前");
BillApplyMoney billApplyMoney = service.selectByPrimaryKey(pk);
asyncLog.info("异步日志查询之后");
System.out.println("线程ID和名称分别是:" + Thread.currentThread().getId() + " / " + Thread.currentThread().getName());
return JsonResult.ok(billApplyMoney);
}
在日志文件中打印出线程名称,同时在IDEA控制台中也打印线程名称,照理说如果是异步写入的日志这两处的线程名称应该不一样,结果日志文件中输出的结果是
2024-06-29 15:36:16.352 INFO asyncLog - [http-nio-7076-exec-2] - 异步日志查询之前
2024-06-29 15:36:16.371 INFO asyncLog - [http-nio-7076-exec-2] - 异步日志查询之后
控制台中输出的是线程ID和名称分别是:86 / http-nio-7076-exec-2
两处的线程名称一样,说明我对于 logback 异步日志的配置错了?
好像没看到你有用到多线程,都是在用当前线程打印的