Java:将 Marshaller 输出重定向到 log4j

Java: Redirect Marshaller output to log4j

我想让我的程序记录给定对象的 XML 使用:

Marshaller.marshal(Object jaxbElement, OutputStream os);

目前,我正在使用 stdout 作为 OutputStream。但是 stdout 没有打印在 log4j 日志文件中。

JAXBContext jc = JAXBContext.newInstance(SomeClass.class);
Marshaller m = jc.createMarshaller();
m.marshal(input, System.out);

如何将此方法的输出重定向到 log4j 日志文件?

谢谢

参见 ByteArrayOutputStream to create an OutputStream and convert to a String with ByteArrayOutputStream#toString()

您修改后的代码:

OutputStream os = new ByteArrayOutputStream();
JAXBContext jc = JAXBContext.newInstance(SomeClass.class);
Marshaller m = jc.createMarshaller();
m.marshal(input, os);
String xml = os.toString();
logger.debug(xml);