My Spring Boot project use XML to communicate with Server. (RESTful API)
And I want to log pretty formatted xml data in my SpringBoot project(use logback for logging)
What's the best way to log pretty formatted xml in Spring?
You have to do something like this, I feel its good way. Change my sysout
with your log statement
.
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
public class YourController{
.
.
.
.
public yourRestMethod() {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputStream("Your XML")));
prettyPrint(doc);
}
public static final void prettyPrint(Document xml) throws Exception {
Transformer tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tf.setOutputProperty(OutputKeys.INDENT, "yes");
Writer out = new StringWriter();
tf.transform(new DOMSource(xml), new StreamResult(out));
System.out.println(out.toString());
}
}