CVA*_*CVA 6 java android logback
logback中有一个名为appender的程序CyclicBufferAppender,但似乎没有相关示例。它有什么作用?它在 a 的上下文中如何工作RollingFileappender?它是与 一起工作RollingFileappender还是独立工作?它类似于吗AsyncAppender?欢迎任何以编程方式编写的示例。
让我分享一个示例,说明我使用它让我的 Spring Boot Web 应用程序在 UI 中显示自己的日志消息。
我有一个CyclicBufferAppender子类,InMemoryAppender其唯一目的是让 Spring 将其作为 bean 进行管理。(受到@NeemePraks 的回答的启发。)
@Component
public class InMemoryAppender extends CyclicBufferAppender<ILoggingEvent> implements SmartLifecycle {
@Override
public boolean isRunning() {
return isStarted();
}
}
Run Code Online (Sandbox Code Playgroud)
我在启动期间添加该组件(这意味着它将错过 Spring Boot 启动日志消息,如链接答案中所示,但我对此表示同意):
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(WebApplication.class, args);
LoggerContext loggerContext = (LoggerContext)LoggerFactory.getILoggerFactory();
Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
rootLogger.addAppender(context.getBean(InMemoryAppender.class));
}
Run Code Online (Sandbox Code Playgroud)
我有一个简单的控制器,只有一个索引页,它读取附加程序的内容:
@Controller
@RequestMapping(path = "/logs")
public class LogController {
public LogController(InMemoryAppender appender) {
this.appender = appender;
}
private final InMemoryAppender appender;
@GetMapping
public String index(Model model) throws Exception {
ILoggingEvent[] events = new ILoggingEvent[appender.getLength()];
for (int i = 0; i < appender.getLength(); i++) {
events[i] = appender.get(i);
}
model.addAttribute("logs", events);
return "logs/index";
}
}
Run Code Online (Sandbox Code Playgroud)
最后是一个简单的 Thymeleaf 页面来显示日志:
<h1>Logs</h1>
<table style="border-collapse: separate; border-spacing: 2px;">
<thead>
<tr>
<th scope="col">Timestamp</th>
<th scope="col">Level</th>
<th scope="col">Message</th>
</tr>
</thead>
<tbody>
<tr th:each="log: ${logs}" th:object="${log}">
<td th:text="*{#dates.format(timeStamp, 'yyyy-MM-dd HH:mm:ss.SSS')}" style="white-space: nowrap;">[timestamp]</td>
<td th:text="*{level}">[level]</td>
<td th:text="*{message}">[message]</td>
</tr>
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
它是这样的:
| 归档时间: |
|
| 查看次数: |
441 次 |
| 最近记录: |