javax.mail.Session setDebugOut を log4j ロガーにリダイレクトする方法は?
mailSession デバッグのみをロガーにリダイレクトすることは可能ですか?
つまり、次のようなソリューションがあります
これにより、すべての標準出力が log4j に移動するように再割り当てされます
--System.setOut(新しい Log4jStream())
よろしくお願いします
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 カテゴリ/アペンダーです。
私は独自の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);
それはトリックをしました:)
独自の OutputStream クラスを作成する
と
mailSession.setDebugOut(new PrintStream(カスタム出力ストリーム オブジェクト));