Configuring and Using the Logger

Depending on what you want to achieve, the logger configuration can be very simple or very complex. I tend not to overcomplicate it and keep it as simple as possible. At the end of the day, there are only a handful of things you need in your logger configuration:

• The logging level. How much output do I want my logger to produce? If the tool is mature, well tested and stable, realistically I would set the log level to ERROR, but if I'm developing, I'd probably stick to DEBUG.

• The log destination. Do I want log messages on screen or in the file? It is best to write it to a file, especially if you are using multiple loggers, one for application status messages and another for systems that you are managing or monitoring.

• The logging message format. The default logger message format is not very informative, so you might want to add additional fields to it, which is very simple to achieve.

Fortunately, the logging module provides a basicConfig method, which allows you to set all of these with one function call:

import logging logging.basicConfig(level=logging.DEBUG, filename='NSLib.log', format="%(asctime)s [%(levelname)s] (%(funcName)s() (%(filename)s:%(lineno)d)) %(message)s")

As you might have already guessed, setting the logging level is trivial; you just need to use one of the defined internal variables, whose names match the log level names we used previously: DEBUG, INFO, WARNING, ERROR or CRITICAL. The log output destination is just a filename. If you do not specify any filename, the logging module will use standard output (stdout) to write all messages.

The logging format is a bit more complicated. The format must be defined following Python string formatting rules, assuming that right argument is a dictionary. The standard convention of formatting a string in Python with parameters in a hash array is as follows:

>>> string = "%(var1)s %(var2)d %(var3)s" % {'var1': 'I bought', 'var2': 3, 'var3':w

Just as in our example, the logging module expects a formatted string on the left of the % operator and provides a standard prepopulated dictionary as the right argument. Table 2-4 lists the most useful parameters that you might want to use in the logging format string.

Table 2-4. Predefined Dictionary Fields That Can Be Used in a logging Format String

Level Description

%(asctime)s The time when the log message was presented, in human-readable form, such as 2009-07-07 14:04:39,462. The number after the comma is the time portion in milliseconds.

%(levelname)s A string representing the log level. Possible default values: DEBUG, INFO, WARNING, ERROR or CRITICAL.

%(funcName)s The name of the function where the logging message was generated.

%(filename)s The name of the file where the logging call was made. This does not contain the full path to the file, just the filename portion.

%(module)s The name of the module that generated the logging call. This is same as the filename with extension stripped out.

%(lineno)d The line number in the file that issued the logging call. Not always available.

%(message)s The actual logging message processed as msg % args in the following format: logging.debug(msg, args)

Once you have configured the logging module, using it is extremely simple—all you have to do is initialize a new instance of the logger and call its methods to write appropriate log messages:

Listing 2-27. Initialising a new logger instance logging.basicConfig(level=logging.DEBUG, filename='NSLib.log', format="%(asctime)s [%(levelname)s] (%(funcName)s() (%(filename)s:%(lineno)d)) %(message)s")

logger = logging.getLogger()

logger.critical('Simple message...') logger.error('Message with one argument: %s', strl)

logger.warning('Message with two arguments. String %s and digit: %d', (msg, val)) try:

logger.critical('An exception has occurred! Stack trace below:', exc_info=True)

As you can see, the logging module is very flexible, yet easy to configure. Use it as much as possible and try to avoid old-style logging using print statements.

Was this article helpful?

0 0

Post a comment