package org.slf4j.impl; import org.slf4j.MDC; import org.slf4j.helpers.BasicMDCAdapter; import java.util.logging.Formatter; import java.util.logging.LogRecord; import java.util.Set; import java.util.Arrays; /** * Implementation of {@link java.util.logging.Formatter} that generates xml in the log4j format. *

* The generated xml corresponds 100% with what is generated by * log4j's XMLLayout *

* The MDC properties will only be correct when format is called from the same thread * that generated the LogRecord. *

* The file and line attributes in the locationInfo element will always be "?" * since LogRecord does not provide that info. *

* The implementation is heavily based on XMLLayout *

*/ public class Log4jXmlFormatter extends Formatter { private final int DEFAULT_SIZE = 256; private final int UPPER_LIMIT = 2048; private StringBuffer buf = new StringBuffer(DEFAULT_SIZE); private boolean locationInfo = false; private boolean properties = false; /** * The LocationInfo option takes a boolean value. By default, * it is set to false which means there will be no location * information output by this layout. If the the option is set to * true, then the file name and line number of the statement at the * origin of the log statement will be output. * @param flag whether locationInfo should be output by this layout **/ public void setLocationInfo(boolean flag) { locationInfo = flag; } /** Returns the current value of the LocationInfo option. * @return whether locationInfo will be output by this layout */ public boolean getLocationInfo() { return locationInfo; } /** * Sets whether MDC key-value pairs should be output, default false. * @param flag new value. */ public void setProperties(final boolean flag) { properties = flag; } /** * Gets whether MDC key-value pairs should be output. * @return true if MDC key-value pairs are output. */ public boolean getProperties() { return properties; } public String format(final LogRecord record) { // Reset working buffer. If the buffer is too large, then we need a new // one in order to avoid the penalty of creating a large array. if (buf.capacity() > UPPER_LIMIT) { buf = new StringBuffer(DEFAULT_SIZE); } else { buf.setLength(0); } buf.append("\r\n"); buf.append("\r\n"); if (record.getThrown() != null) { String[] s = Transform.getThrowableStrRep(record.getThrown()); if (s != null) { buf.append("\r\n"); } } if (locationInfo) { buf.append("\r\n"); } if (properties) { if (MDC.getMDCAdapter() instanceof BasicMDCAdapter) { BasicMDCAdapter mdcAdapter = (BasicMDCAdapter) MDC.getMDCAdapter(); Set keySet = mdcAdapter.getKeys(); if (keySet != null && keySet.size() > 0) { buf.append("\r\n"); Object[] keys = keySet.toArray(); Arrays.sort(keys); for (int i = 0; i < keys.length; i++) { String key = keys[i].toString(); Object val = mdcAdapter.get(key); if (val != null) { buf.append("\r\n"); } } buf.append("\r\n"); } } } buf.append("\r\n\r\n"); return buf.toString(); } }