Java EventPlayer-class And Method Code Example
Here is an example of using the EventPlayer class from the logback library:
import ch.qos.logback.core.Context;
import ch.qos.logback.core.joran.event.SaxEvent;
import ch.qos.logback.core.joran.spi.JoranException;
import ch.qos.logback.core.spi.ContextAwareBase;
import ch.qos.logback.core.spi.LifeCycle;
import ch.qos.logback.core.status.Status;
import ch.qos.logback.core.status.StatusManager;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
public class EventPlayerExample {
public static void main(String[] args) throws JoranException, IOException {
String configFile = "logback.xml";
FileInputStream inputStream = new FileInputStream(configFile);
List<SaxEvent> eventList = new SaxEventRecorder().recordEvents(inputStream);
Context context = new LoggerContext();
EventPlayer eventPlayer = new EventPlayer(context);
eventPlayer.play(eventList);
Logger logger = LoggerFactory.getLogger(EventPlayerExample.class);
logger.debug("This is a debug message.");
logger.info("This is an info message.");
logger.warn("This is a warning message.");
logger.error("This is an error message.");
}
}
In this example, a EventPlayer object is instantiated, and a XML file "logback.xml" is read and recorded as event List using SaxEventRecorder, this list of events is then passed to EventPlayer to play those events.
The EventPlayer reads the events and performs the actions they represent, such as adding appenders to a logger or setting the logging level.
Once the EventPlayer is done, you can use a logger to log messages as usual.
It is worth noticing that this example uses an XML configuration file to configure the logger, but it's also possible to configure logback programmatically.