Search code examples
javaswinglog4jlog4j2

Print Log4j2 output into JTextArea


I have a JTextArea in my program which I would like to display the program's logs. I've done some digging and found OutputStreamAppender in the Log4j2 documentation, which I assume I could use to output logs to an OutputStream which I could then pipe into the JTextArea. Unfortunately there isn't much documentation (at least that I could find) on this. Am I on the right track here? If so, how do I use OutputStreamAppender? If not, what should I be doing? I'd rather not create my own Appender.

Thanks


Solution

  • Maybe try something like (quick and dirty - you'd definitely want to guard against endless looping):

    import java.time.format.*;
    import java.time.*;
    import java.util.Comparator;
    import java.nio.file.*;
    import java.io.IOException;
    
    public class FName {
        public static void main(String[] args) {
            try {
                //System.out.println(FName.getLatestLogFileName(Path.of("/tmp")));
                System.out.println(FName.findLatestLogFileName(Path.of("/tmp")));
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    
        public static Path findLatestLogFileName(Path logsDir) throws Exception {
            // Tighten this pattern up as necessary
            final String LOGFILE_PAT =".*\\.log";
            return Files.find(logsDir, 1, (p, attr) ->p.getFileName().toString().matches(LOGFILE_PAT)).
                sorted(Comparator.comparingLong(p ->p.toFile().lastModified())).
                reduce((first, second) -> second).
                orElse(null);
        }
    
        public static Path getLatestLogFileName(Path logsDir) {
            Path result = null;
            LocalDateTime ldt = LocalDateTime.now();
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd MMMM uuuu HH.mm.ss");
            boolean foundLogFile = false;
            while (result == null) {
                Path test = logsDir.resolve(Path.of(dtf.format(ldt) + ".log"));
                if (Files.exists(test)) {
                    result = test;
                } else {
                    ldt = ldt.minusSeconds(1);
                }
            }
            return result;
        }
    }