This tutorial will show you how to write and configure a XML logging service. This service will be able to write the log events to XML files.
First of all, we will specify the format used for writting the log records to XML file. We do it by creating a Document Type Definition (DTD) for it:
<!ELEMENT log (message?,error?)> <!ATTLIST log time CDATA level CDATA facility CDATA> <!ELEMENT message (#PCDATA)> <!ELEMENT error (#PCDATA)> <!ATTLIST error class CDATA #REQUIRED>
This definition can be found also in the "lib/xmlLogger.dtd" distribution file.
As you can see, each log record includes and optional <message> and <error> elements, as well as the "time", "level" and "facility" attributes. The error element must have the required "class" attribute with the fully specified class name of the Java error or exception instance.
A full log record would then look like this:
<log time="03/08/2003 12:34" level="ERROR" facility="server"> <message>An error occured</message> <error class="com.domain.stuff.StrangeException">Something's wrong!</error> </log>
The XMLLogger class created in this tutorial will be member of the SK.gnome.dwarf.sample package. You can find it already precompiled in the "lib/dwarf.jar" class library coming with the distribution. The source file can be found in the "src/SK/gnome/dwarf/sample" directory.
To develop the logging service we will use the SK.gnome.dwarf.log package. Since the service will write to a XML file, we will choose and extend the FileLogger class. This class provides almost everything we do need. It can initialize an output file and write to it, and has a couple of setter methods to specify the output format of the logged records. Therefore we need to customize just two things:
Let's see the commented source code of the logging service now. The init(Server) method is redefined so that it writes the XML header first if the length of file is null, i.e. the file has been just created. The protected write(...) method has been overriden to write the log records according to XML standard rules and the DTD specification. Please note that in order to save space and make the logger a little more efficient we do not indent the nested XML elements.
Once we have created the new logging service, we may include it to an application. A typical XML-based configuration entry for the XMLLogger may look like this:
<!-- LOG SERVER --> <service class=".log.LogServer" name="Log Server">
<set name="logFacility">log</set> <service class=".sample.XMLLogger" name="XML Logger">
<set name="encoding">UTF-8</set> <!-- UTF-8 is default -->
<!-- OTHER LOGGERS COMES HERE -->
Return to the main page.