Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect javax.mail.Session setDebugOut to log4j logger?

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

like image 354
webgt Avatar asked Jan 22 '10 15:01

webgt


2 Answers

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.

like image 97
Lukáš Rampa Avatar answered Sep 28 '22 06:09

Lukáš Rampa


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

like image 33
Bernhard Avatar answered Sep 28 '22 05:09

Bernhard