4

This is what I'm trying to do:

Logger logger = LogManager.getLogManager().getLogger(Logger.GLOBAL_LOGGER_NAME);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Handler handler = new StreamHandler(stream, new SimpleFormatter());
logger.addHandler(handler);
org.slf4j.LoggerFactory.getLogger("com.example").info("foo");
logger.removeHandler(handler);
assert stream.toString().contains("foo");

It's a mix of SLF4J and JUL. stream is empty at the end of the script. Why?

MaDa
  • 10,511
  • 9
  • 46
  • 84
yegor256
  • 102,010
  • 123
  • 446
  • 597

1 Answers1

0

The StreamHandler only writes the formatter 'head' if a record is formatted. Conditionally the 'head' and 'tail' are written if the handler is closed. All of that seems to indicate that no LogRecord was consumed by the StreamHandler. The SimpleFormatter uses empty string for both the head and tail so that doesn't help in troubleshooting.

  1. Check levels/priorities of all the loggers, appenders and handlers and ensure they are set correctly.
  2. Use Logger.getLogger(Logger.GLOBAL_LOGGER_NAME) instead of the LogManager.
  3. Use a static final reference to hold your logger.
  4. Call close on your handler.
  5. Use XMLFormatter to help troubleshoot since it has head and tail output.
  6. Read slf4j + java.util.logging: how to configure?
Community
  • 1
  • 1
jmehrens
  • 10,580
  • 1
  • 38
  • 47