How can I get XML-structured data in each line with Log4j XMLLayout?
Using the Log4J XMLLayout, I want to put a sequence of fields, wrapped in tags, inside each log-event (log-li开发者_如何转开发ne). <x>some info</x> <y>more info</y>.
This seems a natural way, in the context of an XML logger, to achieve a more structured log. Is there a standard way of doing this, or do I have to build the string with these tags myself?
I could also use a PatternLayout with XML tags wrapping certain fields. I'd have to escape the XML myself, and it seems that XMLLayout should be the one to use for XML.
Another problem is that XMLLayout puts the log-line into a CDATA block, which of course means that any XML in the line is not parseable as XML.
There doesn't seem to be built in functionality for this.
I'd suggest doing this: since you already have log4j, you have it's source code.
Find the file org.apache.log4j.xml.XMLLayout
. Copy it, rename it's package name to something that will fit into your application, simply strip \r\n
where appropriate (this file isn't large, so it shouldn't be a problem) and make a reference in log4j's configuration file to use your new layout.
When I was using log4j XMLLayout to output xml data I just used
logger.info("]]>"+xmlMsg+"<![CDATA[");
This is the lazy way, but it worked for me as not all my log messages were XML so the ones that were not remained escaped.
精彩评论