Home > Net >  Why StreamHandler doesn't catch log messages?
Why StreamHandler doesn't catch log messages?

Time:11-16

What is wrong with this code?

import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.logging.SimpleFormatter;
import java.util.logging.Logger;
import java.util.logging.StreamHandler;

Logger log = Logger.getLogger("foo");
log.setUseParentHandlers(false);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
log.addHandler(new StreamHandler(baos, new SimpleFormatter()));
log.info("test");
assert baos.toByteArray().length > 0;

It fails since baos is empty. Why it's empty?

CodePudding user response:

It requires flushing

Handler handler = new StreamHandler(outputStream, new SimpleFormatter());
log.addHandler(handler);
log.info("test");
handler.flush();

Now it's 44 bytes

By the way, enjoyed the books

  • Related