10

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

Martin Schröder
  • 4,176
  • 7
  • 47
  • 81
webgt
  • 185
  • 2
  • 7
  • 1
    Just stumbled on this old post. There is now also the option to just use a jul->slf4j bridge `java.util.logging.Logger.getLogger("javax.mail")` without using the PrintStream debug option. – ST-DDT Jun 01 '17 at 13:00

3 Answers3

13

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.

Lukáš Rampa
  • 877
  • 1
  • 8
  • 14
3

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 :)

Bernhard
  • 2,541
  • 1
  • 26
  • 24
2

Write your own OutputStream class

and

mailSession.setDebugOut(new PrintStream(your custom aoutput stream object));

webgt
  • 185
  • 2
  • 7