1 package org.simantics.logging;
3 import java.nio.file.Files;
4 import java.nio.file.Path;
5 import java.nio.file.Paths;
6 import java.util.ArrayList;
7 import java.util.Iterator;
9 import java.util.stream.Collectors;
11 import org.slf4j.LoggerFactory;
13 import ch.qos.logback.classic.Logger;
14 import ch.qos.logback.classic.LoggerContext;
15 import ch.qos.logback.classic.spi.ILoggingEvent;
16 import ch.qos.logback.core.Appender;
17 import ch.qos.logback.core.FileAppender;
18 import ch.qos.logback.core.rolling.RollingFileAppender;
19 import ch.qos.logback.core.spi.AppenderAttachable;
21 public class LogbackLogProvider implements LogProvider {
23 private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(LogbackLogProvider.class);
26 public List<Path> get() {
27 List<Path> logs = new ArrayList<>();
29 LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
30 Logger logger = context.getLogger(Logger.ROOT_LOGGER_NAME);
31 Iterator<Appender<ILoggingEvent>> appenderIter = logger.iteratorForAppenders();
32 while (appenderIter.hasNext()) {
33 FileAppender<ILoggingEvent> appender = findFileAppender(appenderIter.next());
34 if (appender != null) {
35 String logFile = ((FileAppender<ILoggingEvent>)appender).getFile();
36 Path log = Paths.get(logFile).toAbsolutePath();
37 if (appender instanceof RollingFileAppender) {
39 Path parent = log.getParent();
40 List<Path> newLogs = Files.walk(parent).collect(Collectors.toList());
41 if (LOGGER.isDebugEnabled())
42 LOGGER.debug("Found {} from {}", newLogs, appender);
48 if (LOGGER.isDebugEnabled()) {
49 LOGGER.debug("Appender is not {} but is {} instead", FileAppender.class.getName(), appender != null ? appender.getClass().getName() : "null");
53 } catch (ClassCastException e) {
54 // Okay, we are not using logback here
55 if (LOGGER.isDebugEnabled())
56 LOGGER.debug("Seems like we are not using logback but {} instead", LoggerFactory.getILoggerFactory(), e);
57 } catch (Throwable t) {
58 LOGGER.error("Could not collect logs", t);
60 if (LOGGER.isDebugEnabled())
61 LOGGER.debug("Found {} log files : {}", logs.size(), logs);
65 private static FileAppender<ILoggingEvent> findFileAppender(Appender<ILoggingEvent> appender) {
66 if (appender instanceof AppenderAttachable) {
67 // Ok, has child appender
68 Iterator<Appender<ILoggingEvent>> children = ((AppenderAttachable<ILoggingEvent>) appender).iteratorForAppenders();
69 while (children.hasNext()) {
70 FileAppender<ILoggingEvent> app = findFileAppender(children.next());
71 // TODO: returns only first FileAppender that it founds but not a collection
76 } else if (appender instanceof FileAppender) {
77 return (FileAppender<ILoggingEvent>) appender;