Extending logger levels

The logging module has five predefined levels of importance. Each level has a global variable (or two) with the level number. The level of importance represents a spectrum of optionality, from debugging messages (rarely important enough to show) to critical or fatal errors (always important), as shown in the following table:

Logging module variable

Value

DEBUG

10

INFO

20

WARNING or WARN

30

ERROR

40

CRITICAL or FATAL

50

 

We can add additional levels for even more nuanced control over what messages are passed or rejected. For example, some applications support multiple levels of verbosity. Similarly, some applications include multiple levels of debugging details. We might want to add an additional, verbose output level, set to 15, for example. This fits between information and debugging. It can follow the pattern of informative messages without devolving to the details of a debugging log.

For ordinary, silent processing, we might set the logging level to logging.WARNING so that only warnings and errors are shown. For the first level of verbosity, we can set the level of logging.INFO to see informational messages. For the second level of verbosity, we might want to add a level with a value of 15 and set the root logger to include this new level.

We can use the following to define our new level of verbose messages:

logging.addLevelName(15, "VERBOSE") 
logging.VERBOSE = 15 

This code needs to be written prior to the configuration of the loggers. It would be part of a top-level, main script. We can use our new levels via the Logger.log( ) method, which takes the level number as an argument, as follows:

self.logger.log(logging.VERBOSE, "Some Message") 

While there's little overhead to add levels such as these, they can be overused. The subtlety is that a level conflates multiple concepts—visibility and erroneous behavior—into a single numeric code. The levels should be confined to a simple visibility or error spectrum. Anything more complex must be done via the Logger names or the actual Filter objects.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset