The Configuration File

There are many ways of storing configuration data for your applications. I prefer to use XML documents for the following reasons:

• Python has built-in libraries for parsing XML and as such, accessing configuration data is simple.

• Syntax validation happens automatically when the configuration file is fed to the XML parser, so I need not worry about checking the syntax of the configuration file.

• XML documents have a clearly defined unambiguous structure that allows me to implement hierarchical structures should I need to.

There is also a practical downside of using XML—it's not really human-friendly. However, by using appropriate editors that can do syntax highlighting we can mitigate this. Nowadays most editors support this functionality. The ViM editor, which is available on nearly all Linux distributions, is also able to highlight XML syntax.

Listing 7-10 is a simple configuration file to catch majority of the File Not Found exceptions.

Listing 7-10. A configuration file with two rules

<?xml version="1.0"?> <config>

<exception_types>

<exception logline="" headline=""

body="java\.io\.FileNotFoundException: .+ \(No such file or^

directory\)"

group="File not found exception" desc="File not found exception"

<exception logline="" headline=""

body="java\.io\.FileNotFoundException: .+ \(Permission denied\)" group="Permission denied exception" desc="Permission denied exception"

</exception_types> </config>

The configuration file starts with a document identification string that tells the parsers it is an XML version 1.0 document. For basic processing this information isn't strictly required and can be omitted, but for completeness it's best to adhere to the specification.

The root element of the XML configuration files is the <config> tag, which encompasses all other configuration items. Now I have the option of putting exception declarations directly within the <config> tags, and since I have not planned to have anything else in my configuration file it would just be fine. However if I later added any new type of configuration items, for example something that affects reporting, it would not logically fit. So it is always a good idea to create a branch tag and place all elements of a given type within it. Therefore I define a new domain element, which I'm going to call <exception_types>. All declarations for each individual exception type are going to be defined here.

As you can see the actual exception declaration is pretty straightforward. I have three placeholders for regular expressions followed by a description and group name fields.

Was this article helpful?

0 0

Post a comment