如何将javax.mail.Session setDebugOut重定向到log4j logger?
是否可以仅将mailSession调试重定向到记录器?
我的意思是,有像
这样的解决方案将所有标准输出重新分配到log4j
- System.setOut(new Log4jStream())
最好的问候
答案 0 :(得分:10)
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类别/ Appender。
答案 1 :(得分: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 :(得分:2)
编写自己的OutputStream类
和
mailSession.setDebugOut(new PrintStream(您的自定义输出流对象));