10

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

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

我的意思是,有像这样的解决方案

链接文本

它将所有标准输出重新分配到 log4j

--System.setOut(新 Log4jStream())

此致

4

3 回答 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 类别/附加程序。

于 2011-07-09T17:30:39.990 回答
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);

那成功了:)

于 2013-03-14T17:09:19.500 回答
2

编写自己的 OutputStream 类

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

于 2010-01-28T08:48:23.587 回答