How to redirect javax.mail.Session setDebugOut to log4j logger?
Is it possible to redirect only mailSession debug out to logger?
I mean, there are solutions like
link text
which reassigns all standard output to go to log4j
--System.setOut(new Log4jStream())
Best Regards
Apache Commons Exec library contains useful class LogOutputStream, which you can use for this exact purpose:
LogOutputStream losStdOut = new LogOutputStream() {
@Override
protected void processLine(String line, int level) {
cat.debug(line);
}
};
Session session = Session.getDefaultInstance(new Properties(), null);
session.setDebugOut(new PrintStream(losStdOut));
cat is obviously log4j Category/Appender.
i created an own filteroutputstream (you could also use the org.apache.logging.Logger instead of the SLF)
public class LogStream extends FilterOutputStream
{
private static org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(LogStream.class);
private static final OutputStream bos = new ByteArrayOutputStream();
public LogStream(OutputStream out)
{
// initialize parent with my bytearray (which was never used)
super(bos);
}
@Override
public void flush() throws IOException
{
// this was never called in my test
bos.flush();
if (bos.size() > 0) LOG.info(bos.toString());
bos.reset();
}
@Override
public void write(byte[] b) throws IOException
{
LOG.info(new String(b));
}
@Override
public void write(byte[] b, int off, int len) throws IOException
{
LOG.info(new String(b, off, len));
}
@Override
public void write(int b) throws IOException
{
write(new byte[] { (byte) b });
}
}
then i redirected the javamail to my output
// redirect the output to our logstream
javax.mail.Session def = javax.mail.Session.getDefaultInstance(new Properties());
def.setDebugOut(new PrintStream(new LogStream(null)));
def.setDebug(true);
that did the trick :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With