如何将javax.mail.Session的setDebugOut重定向到log4j日志记录器?

10

如何将javax.mail.Session setDebugOut重定向到log4j日志记录器?

是否可能仅将mailSession调试输出重定向到记录器?

我的意思是,有像

链接文本

这样的解决方案,将所有标准输出重新分配到log4j中

--System.setOut(new Log4jStream())

最好的祝福


1
刚刚偶然发现了这篇旧帖子。现在也有一个选项,可以只使用 jul->slf4j 桥接器 java.util.logging.Logger.getLogger("javax.mail"),而不使用 PrintStream 调试选项。 - ST-DDT
3个回答

13

Apache Commons Exec库包含一个有用的类LogOutputStream,你可以用它来实现这个目的:

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显然是log4j的Category/Appender。


3
我创建了一个自己的FilterOutputStream(您也可以使用org.apache.logging.Logger代替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 });
            }
    }

然后我将Javamail重定向到我的输出。
// 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);

那就搞定了 :)

2

编写自己的OutputStream类

并且

mailSession.setDebugOut(new PrintStream(您自定义的输出流对象));


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接