如何将javax.mail.Session setDebugOut重定向到log4j日志记录器?
是否可能仅将mailSession调试输出重定向到记录器?
我的意思是,有像
这样的解决方案,将所有标准输出重新分配到log4j中
--System.setOut(new 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的Category/Appender。
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 });
}
}
// 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(您自定义的输出流对象));
java.util.logging.Logger.getLogger("javax.mail")
,而不使用 PrintStream 调试选项。 - ST-DDT