Python Standard Logging in Sugar

From OLPC
Revision as of 12:04, 9 July 2008 by Fanwar (talk | contribs)
Jump to: navigation, search

What is the overall structure of python standard logging that I will use in Sugar?

Sugar uses Python's Standard Logging<ref>OnLamp.com-- Python Standard Logging</ref><ref>Python Library Reference -- Logging</ref> pretty much without modification. The diagram below conceptualizes how logging generally works.

How do I write to a log in my activity code?

Sugar uses python's standard logging. The following code shows how to output something at the debug log level. The log message will be written to the standard log output destination (usually the console).

   import logging
   _logger = logging.getLogger('annotate-activity')
   ...
        _logger.debug('starting activity')

How do I send my log output to multiple destinations, including a file and the console?

The code example below sets up the activity to output its logs to several destinations. In particular, we output to a file called 'Annotate.activity.log' in sugar's standard logging directory and to the console. There are many different types of handler objects that you can output to at the same time, depending upon your debugging and tracking needs.

from sugar import logger
import logging
import logging.config
_logger = logging.getLogger('activity-annotate')
...
    #### Method: __init__, initialize this AnnotateActivity instance
    def __init__(self, handle):
        activity.Activity.__init__(self, handle)

        #Get the standard logging directory. 
        std_log_dir = logger.get_logs_dir()

        #First log handler: outputs to a file called 'Annotate.activity.log'
        file_handler = logging.FileHandler(os.path.join(std_log_dir, 'Annotate.activity.log'))
        file_formatter = logging.Formatter('%(name)s -- %(asctime)s %(levelname)s:\n %(message)s\n')
        file_handler.setFormatter(file_formatter)
        _logger.addHandler(file_handler)

        #Second log handler: outputs to a the console, using a slightly different output structure
        console_handler = logging.StreamHandler()
        console_formatter = logging.Formatter('%(name)s %(levelname)s ||| %(message)s')
        console_handler.setFormatter(console_formatter)
        _logger.addHandler(console_handler)
        ...
        _logger.debug('Creating annotate activity UI')

Notes

<references />