0

I have implemented Java logging with a properties file. There I use a custom logger with a filehandler and a custom handler. My problem is, that the log level of the custom handler is not working. This is my configuration:

studium.logger.useParentHandlers = false

studium.logger.ProjectLogger.handlers = java.util.logging.FileHandler, studium.logger.WindowHandler


studium.logger.ProjectLogger.level = FINEST


studium.logger.WindowHandler.formatter = studium.logger.formatter.TextAreaFormatter
studium.logger.WindowHandler.level = INFO

java.util.logging.FileHandler.level = FINEST
java.util.logging.FileHandler.formatter = studium.logger.formatter.FileFormatter
java.util.logging.FileHandler.append    = true
java.util.logging.FileHandler.pattern   = log.txt

The filehandler is working fine. It is logged nicely in my log file. But with my WindowHandler I still get all logs with the loglevel Fine and not only Info and Warning

here is my WindowHandler:

public class WindowHandler extends StreamHandler {

    private JTextArea textArea;

    public WindowHandler() {
        super();
        this.textArea = MainFrame.out;
    }

    @Override
    public void publish(LogRecord record) {
        textArea.append(getFormatter().format(record));
    }

    public JTextArea getTextArea() {
        return textArea;
    }

    public void setTextArea(JTextArea textArea) {
        this.textArea = textArea;
    }

}

And here is the output in my textArea:

FINE Test log level FINE
WARNING Test log level WARNING

What am I missing?

jmehrens
  • 10,580
  • 1
  • 38
  • 47
TheSilent
  • 43
  • 1
  • 7

1 Answers1

0

Ignoring the Swing threading issue present in your code, you have to call Handler.isLoggable(Record) so your publish method respects the log level you have set.

public void publish(LogRecord record) {
    if (isLoggable(record)) {
       textArea.append(getFormatter().format(record));
    }
}

Fixing the threading issues and exception handling you should end up with something like:

@Override
public void publish(LogRecord record) {
    if (isLoggable(record)) {
        try {
            final String val = getFormatter().format(record);
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    try {
                        getArea().append(val);
                    } catch (RuntimeException e) {
                        reportError(val, e, ErrorManager.WRITE_FAILURE);
                    }
                }
            });
        } catch (RuntimeException e) {
            reportError(null, e, ErrorManager.WRITE_FAILURE);
        }
    }
}

private JTextArea getArea() {
    if (!SwingUtilities.isEventDispatchThread()) {
       throw new IllegalThreadStateException(Thread.currentThread().toString());
    }
    return null; //@todo Implement this.
}
jmehrens
  • 10,580
  • 1
  • 38
  • 47