import javax.xml.transform.*;
import java.util.logging.*;
public class LoggingErrorListener implements ErrorListener {
private Logger logger;
public LoggingErrorListener(Logger logger) {
this.logger = logger;
}
public void warning(TransformerException exception) {
logger.log(Level.WARNING, exception.getMessage(), exception);
// Don't throw an exception and stop the processor
// just for a warning; but do log the problem
}
public void error(TransformerException exception)
throws TransformerException {
logger.log(Level.SEVERE, exception.getMessage(), exception);
// XSLT is not as draconian as XML. There are numerous errors
// which the processor may but does not have to recover from;
// e.g. multiple templates that match a node with the same
// priority. I do not want to allow that so I throw this
// exception here.
throw exception;
}
public void fatalError(TransformerException exception)
throws TransformerException {
logger.log(Level.SEVERE, exception.getMessage(), exception);
// This is an error which the processor cannot recover from;
// e.g. a malformed stylesheet or input document
// so I must throw this exception here.
throw exception;
}
}
The following two methods appear in both
TransformerFactory and
Transformer. They
enable you to set and get the ErrorListener
that the object will report problems to:
public abstract void setErrorListener(ErrorListener listener)
throws IllegalArgumentException;public abstract ErrorListener getErrorListener();
An ErrorListener registered
with a Transformer will report errors
with the transformation.
An ErrorListener registered
with a TransformerFactory will report errors
with the factory’s attempts to create new
Transformer objects. For example,
this code fragment installs separate
LoggingErrorListeners on the
TransformerFactory and the
Transformer object it creates that
will record messages in two different logs.
TransformerFactory factory = TransformerFactory.newInstance();
Logger factoryLogger
= Logger.getLogger("com.macfaq.trax.factory");
ErrorListener factoryListener
= new LoggingErrorListener(factoryLogger);
factory.setErrorListener(factoryListener);
Source source = new StreamSource("FibonacciXMLRPC.xsl");
Transformer stylesheet = factory.newTransformer(source);
Logger transformerLogger
= Logger.getLogger("com.macfaq.trax.transformer");
ErrorListener transformerListener
= new LoggingErrorListener(transformerLogger);
stylesheet.setErrorListener(transformerListener);