The logging module

The logging module contains a series of modules which aim to improve the ease of debugging a system through logging messages to a given stream.

The pyamp.logging.logger.Logger class is the central class to the logging module. It is essentially a wrapper class for the Python logging module and provides extended functionality such as: adding prefixes to the logged messages, and logging colored messages to the console.

The LogLevel class

class pyamp.logging.LogLevel

The LogLevel class contains definitions of all of the various log levels that can be used for logging messages. These levels are designed to make it easier to parse the output of a system to find different types of issues that were encountered at runtime.

  • DEBUG – The debugging log level. Has a value of 10.
  • INFO – The information log level. Has a value of 20.
  • WARN – The warning log level. Has a value of 30.
  • WARNING – The warning log level. Has a value of 30.
  • ERROR – The error log level. Has a value of 40.
  • CRITICAL – The critical log level. Has a value of 50.
  • FATAL – The fatal log level. Has a value of 50.

The LogData class

class pyamp.logging.LogData(logLevel=20, debugLevel=0)

The LogData class provides the ability to store logging data for an entire system in an object that can be easily handled.

The LogData class stores a LogLevel and an integer debug level for a system, and provides the ability to create a named Logger from the stored values.

For example:

# Any Logger objects created from this LogData object will have a
# LogLevel of DEBUG, and a debug level of 10.
logData = LogData(LogLevel.DEBUG, 10)

# Create a logger named 'ExampleLogger' which will log messages
# with a red foreground color.
logger = logData.get("ExampleLogger", Colors.Foreground.Red)

# This message will be displayed
logger.debug("Example message", 2)

# This message will not be displayed
logger.debug("Example message", 11)

LogData objects can be easily passed around which allows the :class::LogLevel and debug level values to be easily propagated throughout the system, rather than having individual values for each system component.

  • logLevel – The log level
  • debugLevel – The debug level
get(name=None, color=0)

Get a new Logger with the given name.

  • name – The name to assign the Logger
  • color – The color to use for the Logger

The Logger class

class pyamp.logging.Logger(name=None, color=0, prefix=<pyamp.logging.prefix.Prefix instance at 0xa2ddc8c>, logLevel=30, debugLevel=0, handler=<logging.StreamHandler instance at 0xa2ddd0c>)

The Logger class provides the ability to log various types of messages to a specific stream, and formats the messages using given Prefix objects.

The Logger class will log each LogLevel with a colored prefix indicating the name of the log level. Logged messages are only displayed in the event that the LogLevel at which they are logged is greater than or equal to the current LogLevel of the Logger which is logging the message. Each LogLevel.DEBUG message can also have an optional debug level specified, which will allow that message to be displayed so long as the specified debug level is less than or equal to the configured debug level of the Logger object.

Each Logger object can be named, and colored, which means that any message logged using that object will be displayed with a prefix indicating the name (and displayed in the specified color) of the object which logged the message.

Logger objects can be given a chain of Prefix objects. Any message logged using that Logger object will then have a series of prefixes added to the front of the message.

Logger objects can also have a handler specified, which specifies the type of stream which will be handled by this Logger. For example, to output to the console a value of logging.StreamHandler could be specified, whereas a value of logging.FileHandler could be specified to log to a specific file.

Example:

# Create a Logger with the name 'Example1'
logger = Logger("Example1")
logger.info("Information message")

# Create a Logger with the name 'Example2', a foreground
# color of Blue, and logs DEBUG messages that have a debug
# level less than or equal to 10.
logger = Logger("Example2", color=Colors.Foreground.Blue,
                logLevel=LogLevel.DEBUG, debugLevel=10)
logger.debug("This message is displayed", 2)
logger.debug("This message is not displayed", 11)

# Create a Logger with the name 'Example3' that only displays
# ERROR messages
logger = Logger("Example3", logLevel=LogLevel.ERROR)
logger.warn("This would not be displayed")
  • name – The name of the Logger
  • color – The color to use for this Logger
  • prefix – The Prefix chain to use for this Logger
  • logLevel – The log level to use for this Logger
  • debugLevel – The debug level
  • handler – The handler to use for this Logger
critical(message, *args, **kwargs)

Log a critical message.

  • message – The message to log
  • args – The arguments
  • kwargs – The keyword arguments
debug(message, level=0, *args, **kwargs)

Log a debug message.

  • message – The message to log
  • level – The debug level
  • args – The arguments
  • kwargs – The keyword arguments
error(message, *args, **kwargs)

Log an error message.

  • message – The message to log
  • args – The arguments
  • kwargs – The keyword arguments
fatal(message, *args, **kwargs)

Log a fatal message.

  • message – The message to log
  • args – The arguments
  • kwargs – The keyword arguments
info(message, *args, **kwargs)

Log an info message.

  • message – The message to log
  • args – The arguments
  • kwargs – The keyword arguments
log(logLevel, message, *args, **kwargs)

Log a message at the given log level.

  • logLevel – The level at which to log
  • message – The message to log
  • args – The arguments
  • kwargs – The keyword arguments
setName(name)

Set the name for this logger.

  • name – The name
setPrefix(prefix)

Set the prefix for this logger.

  • prefix – The prefix
warn(message, *args, **kwargs)

Log a warning message.

  • message – The message to log
  • args – The arguments
  • kwargs – The keyword arguments
warning(message, *args, **kwargs)

Log a warning message.

  • message – The message to log
  • args – The arguments
  • kwargs – The keyword arguments

The SingleLogger class

class pyamp.logging.SingleLogger

The SingleLogger class implements the pyamp.patterns.Borg design pattern for creating a single system wide Logger object.

This allows an entire system to access the same Logger object so that each component can log messages with the same data (e.g., log level, color, prefix, etc).

Create the SingleLogger object.

classmethod createFileLogger(logFile, append=False, logLevel=30)

Create a system-wide FileLogger object.

  • logFile – The log file to use
  • append – True to append to the file, False to overwrite
  • logLevel – The log level for the logger
classmethod createLogger(name, logLevel=30)

Create a system-wide Logger object.

  • name – The name of Logger
  • logLevel – The log level for the logger
classmethod critical(message)

Log the given critical message.

  • message – The message to log
classmethod debug(message)

Log the given debug message.

  • message – The message to log
classmethod error(message)

Log the given error message.

  • message – The message to log
classmethod fatal(message)

Log the given fatal message.

  • message – The message to log
classmethod getInstance()

Get the instance of the Logger object.

classmethod info(message)

Log the given information message.

  • message – The message to log
classmethod log(logLevel, message)

Log the given message at the given log level.

  • logLevel – The log level
  • message – The message to log
classmethod warn(message)

Log the given warning message.

  • message – The message to log
classmethod warning(message)

Log the given warning message.

  • message – The message to log
classmethod write(message)

Write an information message to the logger.

  • message – The message to write

The Colors class

class pyamp.logging.Colors

The Colors class contains two classes which define possible Foreground and Background colors. These colors can be used to colorize console output in a specific way.

class Background

The Background class contains definitions of the following background colors.

  • White_Bold_Underline
  • Blue, and Light_Blue
  • Purple, and Light_Purple
  • Green, and Light_Green
  • Red, and Light_Red
  • Gray, and Light_Gray
  • Cyan, and Light_Cyan
  • Orange, and Light_Yellow
class Colors.Foreground

The Foreground class contains definitions of the following foreground colors.

  • White
  • White_Bold
  • White_Underline
  • Black
  • Blue, and Light_Blue
  • Purple, and Light_Purple
  • Green, and Light_Green
  • Red, and Light_Red
  • Gray, and Light_Gray
  • Cyan, and Light_Cyan
  • Orange, and Light_Yellow

The Prefix class

class pyamp.logging.Prefix(text=None, color=0, prefix=None)

The Prefix class provides the ability to add chain of prefixes to a message. A Prefix contains text which is printed in square brackets before the given message. The following shows an example of the a Prefix for the string “DEBUG”.

Example:

prefix = Prefix(text="DEBUG")

# Prints: [DEBUG]: This is the message
prefix.apply("This is the message")

A Prefix can be colored, and it can contain other prefixes which are appended to the message before adding the current Prefix.

An example of multiple prefixes:

debugPrefix = Prefix(text="DEBUG")
examplePrefix = Prefix(text="example", prefix=debugPrefix)
datePrefix = Prefix(text="03/11/2012", prefix=examplePrefix)

# Prints: [DEBUG]: [example]: [03/11/2012]: This is the message
datePrefix.apply("This is the message")
  • text – The text to display in the Prefix
  • color – The color in which the Prefix will be displayed
  • prefix – The next Prefix in the chain
apply(message, useColors=False)

Apply the chain of Prefixes to the given message.

  • message – The message to apply the Prefix chain to
  • useColors – True to use colors, False otherwise

The FnPrefix class

class pyamp.logging.FnPrefix(function, color=0, prefix=None)

The FnPrefix class provides to ability to create a Prefix whose text results from calling a specified function when the Prefix is applied to a message.

Example:

prefix = FnPrefix(function=lambda: "Hey!")

# Prints: [Hey!]: This is the message
prefix.apply("This is the message")

This class can be used to dynamically create the text used for a prefix by calling a function which returns the desired value for the prefix.

  • function – The function which returns the Prefix text
  • color – The color in which the Prefix will be displayed
  • prefix – The next Prefix in the chain

The TimePrefix class

class pyamp.logging.TimePrefix(format=None, color=0, prefix=None)

The TimePrefix provides the ability to add a Prefix which displays the date and or time when the Prefix is applied to the message in a specified format.

Example:

prefix = TimePrefix(format="%Y-%m-%d")

# Prints: [2012-03-22]: This is the message
prefix.apply("This is the message")

This class is useful for dynamically timestamping logged messages so they can easily be tracked in the system output.

  • format – The format in which the time will be displayed. See the

    man page for ‘date’

  • color – The color in which the Prefix will be displayed

  • prefix – The next prefix in the chain

The Loggable class

class pyamp.logging.Loggable(name=None, logger=None, color=0)

The Loggable class provides the ability to expose the logging methods (i.e., debug, info, warn, warning, error, fatal, critical, and error) on a specific class. This provides the ability to easily log messages throughout a class without needed to specifically create a Logger object.

The Loggable class can be created from either a Logger object, or a LogData object.

  • name – The name of the Logger
  • logger – The LogData, or Logger object to use
  • color – The color of the Logger
critical(message, *args, **kwargs)

Log a critical message.

  • message – The message to log
  • args – The arguments
  • kwargs – The keyword arguments
debug(message, level=0, *args, **kwargs)

Log a debug message.

  • message – The message to log
  • level – The debug level
  • args – The arguments
  • kwargs – The keyword arguments
error(message, *args, **kwargs)

Log an error message.

  • message – The message to log
  • args – The arguments
  • kwargs – The keyword arguments
fatal(message, *args, **kwargs)

Log a fatal message.

  • message – The message to log
  • args – The arguments
  • kwargs – The keyword arguments
info(message, *args, **kwargs)

Log an info message.

  • message – The message to log
  • args – The arguments
  • kwargs – The keyword arguments
log(logLevel, message, *args, **kwargs)

Log a message at the given log level.

  • logLevel – The level at which to log
  • message – The message to log
  • args – The arguments
  • kwargs – The keyword arguments
warn(message, *args, **kwargs)

Log a warning message.

  • message – The message to log
  • args – The arguments
  • kwargs – The keyword arguments
warning(message, *args, **kwargs)

Log a warning message.

  • message – The message to log
  • args – The arguments
  • kwargs – The keyword arguments

The LoggerMeta class

class pyamp.logging.LoggerMeta

The LoggerMeta is a metaclass that provides the ability to create a Logger for a given class. The class has the ability to set the following static class properties.

  • logLevel – Set log level for the logger
  • logPrefix – Set the log prefix for the logger

Any classes that use LoggerMeta as their metaclass will have a ‘logger’ property created, which will be a Logger object with the preset logLevel, and logPrefix.

Example:

class Example:
    __metaclass__ = LoggerMeta
    logLevel = LogLevel.INFO
    logPrefix = Prefix(text="TestPrefix")

if __name__ == '__main__':
    example = Example()

    # Prints: [Example]: [TestPrefix]: This is an information message
    example.logger.info("This is an information message")

The FunctionLoggerMeta class

class pyamp.logging.FunctionLoggerMeta

The FunctionLoggerMeta class is a metaclass that provides the ability to log specific functions of a class. This metaclass uses the Logger object (as created by the LoggerMeta class) to print debug statements as functions of a class are entered and exited.

The following types of functions will NOT be logged:
  • Builtin functions (i.e., the function name ends with ‘__’)
  • Functions that are decorated with the doNotLog() function

All other functions will log a DEBUG message when the function is entered and when the function is exited. This provides an easy way to toggle the ability to view the scope of functions during the runtime of a system.

Example:

class Example:
    __metaclass__ = FunctionLoggerMeta

    def test(self):
        print "This is a test"


if __name__ == '__main__':
    example = Example()

    # Prints:
    #    [DEBUG]: Entering test
    #    This is a test
    #    [DEBUG]: Exiting test
    example.test()

The doNotLog function decorator

pyamp.logging.doNotLog(function)

The doNotLog function is a decorator function which flags a function so that it does not get logged by the FunctionLoggerMeta class.

Any functions decorated with ‘doNotLog’ will be ignored by the FunctionLoggerMeta class.

Example:

class Example:
    __metaclass__ = FunctionLoggerMeta

    # This function will be logged
    def logged(self):
        pass

    # This function will not be logged
    @doNotLog
    def notLogged(self):
        pass