3

Someone know if that's possible to make a listener on the log4j for catching every log from a named method/class ? The finality is to add the retrieved log into a JPanel.

log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="ERROR" name="config">
    <Properties>
        <Property name="LOG_DIR">logs</Property>
        <Property name="ARCHIVE">logs/archive</Property>
        <Property name="PATTERN">%-5level %d [%t] %c:%M(%L): %m%n</Property>
    </Properties>
    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout pattern="${PATTERN}"/>
        </Console>

        <RollingFile name="fileWriter"
                     fileName="${LOG_DIR}/logs.log"
                     filePattern="${ARCHIVE}/logs.log.%d{yyyy-MM-dd-hh-mm}.gz">
            <PatternLayout pattern="${PATTERN}"/>
            <TimeBasedTriggeringPolicy/>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="INFO">
            <AppenderRef ref="fileWriter"/>
        </Root>
    </Loggers>
</Configuration>

Log example

  public class MyClass() {
    private final static Logger logger = LogManager.getLogger();

    public void method() {
      logger.info("Some text...");
      logger.info("More text...");
    }
  }

Thanks!

Remko Popma
  • 35,130
  • 11
  • 92
  • 114
keupsonite
  • 399
  • 3
  • 15

1 Answers1

2

The way I would do this is to write a custom log4j2 appender. This is actually quite easy to do with Log4j 2. Here is an example to get you started: https://stackoverflow.com/a/24220688/1446916

The example prints to the console, but in your case you would append to the text area. (Well actually you want to submit a Runnable to SwingUtils.invokeLater() that appends the text to the text area. Swing demands that all interaction takes place in the AWT event thread.)

The only thing remaining is wiring these two together. You could make the text area available through some static lookup. You may want to think about what to do if the text area is not initialized yet when you receive log events. Drop the event, or queue them and append them later?

Community
  • 1
  • 1
Remko Popma
  • 35,130
  • 11
  • 92
  • 114