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を作成しました(SLFの代わりにorg.apache.logging.Loggerを使用することもできます)

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 に答える