Package helium :: Module logger |
[hide private]
[frames] | no frames]

# Source Code for Module helium.logger

      1  #============================================================================
      2  #Name        : logger.py
      3  #Part of     : Helium
      4
      5  #Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
      6  #All rights reserved.
      7  #This component and the accompanying materials are made available
      8  #under the terms of the License "Eclipse Public License v1.0"
      9  #which accompanies this distribution, and is available
     10  #at the URL "http://www.eclipse.org/legal/epl-v10.html".
     11  #
     12  #Initial Contributors:
     13  #Nokia Corporation - initial contribution.
     14  #
     15  #Contributors:
     16  #
     17  #Description:
     18  #===============================================================================
     19
     20  ##
     21  # Logger module
     22  # Description : Port to python of the ISIS::Logger3 perl module
     23  #
     24  # 1.0.0 (13/12/2006)
     25  #  - First version of the module.
     26  ##
     27
     28  # pylint: disable-msg=E1101,E1103
     29
     30  import codecs
     31  import xml.dom.minidom
     32  import datetime
     33  from os import popen
     34  import traceback
     35
     36  #
     37  # This is an Internal helper call.
     38  #
     39 -class _CustomizePrint(object):
     40
     41      ##
     42      # Initialise the instance content
     43      # @param logger a Logger instance
     44      # @param name method name (e.g. Print, Error), could be any strings
     45 -    def __init__(self, logger, name):
     46          self.__logger = logger
     47          self.__name = name
     48
     49      ##
     50      # Make this object callable. Call _print from the logger instance.
     51      # @params *args a list of arguments
     52 -    def __call__(self, *args):
     53          self.__logger._print(self.__name, args)
     54
     55  ##
     56  # The Logger enables to create xml logging in Python.
     57  #
     58 -class Logger(object):
     59
     60      ##
     61      # Constructor of the Logger.
     62 -    def __init__(self):
     63          self.__step = 1
     64          self.__doc = xml.dom.minidom.Document()
     65          self.__lognode = self.__doc.createElementNS("", "__log")
     66          self.__header = self.__doc.createElementNS("", "__header")
     67          self.__footer = self.__doc.createElementNS("", "__footer")
     68          self.__summary = self.__doc.createElementNS("", "__summary")
     69          self.__lognode.appendChild(self.__header)
     70          self.__lognode.appendChild(self.__summary)
     71          self.__lognode.appendChild(self.__footer)
     72          self.__lognode.setAttributeNS("", "date", "%s" % datetime.datetime.now().ctime())
     73          self.__footer.setAttributeNS("", "title", "")
     74          self.__footer.setAttributeNS("", "subtitle", "")
     75          self.__doc.appendChild(self.__lognode)
     76          self.__build = self.__doc.createElementNS("", "build")
     77          self.__lognode.appendChild(self.__build)
     78          self.__current_node = self.__build
     79          self.__stack = []
     80          self.__verbose = True
     81          #<__log date="Wed Dec  6 03:07:25 2006">
     82
     83      ##
     84      # Set the url of interface to use.
     85 -    def SetInterface(self, url):
     86          self.__lognode.setAttributeNS("", "interface", url)
     87
     88      ##
     89      # Enable/Disable shell output
     90      # @param v boolean to set the logger output
     91 -    def SetVerbose(self, v):
     92          self.__verbose = v
     93
     94      ##
     95      # Set the title of the document
     96      # @param title the title to set
     97 -    def SetTitle(self, title):
     98          self.__header.setAttributeNS("", "title", title)
     99
    100      ##
    101      # Set the subtitle of the document
    102      # @param subtitle the subtitle to set
    103 -    def SetSubTitle(self, title):
    104          self.__header.setAttributeNS("", "subtitle", title)
    105
    106      ##
    107      # Set the sumamry title
    108      # @param title the title to set
    109 -    def SetSummaryTitle(self, title):
    110          self.__summary.setAttributeNS("", "title", title)
    111
    112      ##
    113      # Creates a summary couple.
    114      # @param tag the description
    115      # @param value the value
    116 -    def AddSummaryElement(self, tag, value):
    117          e = self.__doc.createElementNS("", "__elmt")
    118          e.setAttributeNS("", "tag", tag)
    119          e.setAttributeNS("", "val", value)
    120          self.__summary.appendChild(e)
    121
    122
    123      ##
    124      # Open a MainContent section.
    125      # @param title title of the MainContent section
    126 -    def OpenMainContent(self, title=""):
    127          self.__stack.append(self.__current_node)
    128          n = self.__doc.createElementNS("", "task")
    129          n.setAttributeNS("", "name", title)
    130          n.setAttributeNS("", "type", "maincontent")
    131          n.setAttributeNS("", "time", datetime.datetime.now().ctime())
    132          self.__current_node.appendChild(n)
    133          self.__current_node = n
    134          if self.__verbose:
    135              print ("---------------------------------------------------------------------")
    136              print ("  %s" % title)
    137              print ("---------------------------------------------------------------------")
    138
    139
    140      ##
    141      # Close the current main content section.
    142      # Make sure you have closed other Event/Section first
    143 -    def CloseMainContent(self):
    144          if self.__current_node.nodeName != "task" and not (self.__current_node.attributes.has_key('type') and self.__current_node.attributes['type']=="maincontent"):
    145              raise Exception("not closing a 'maincontent' typed node")
    146          self.__current_node = self.__stack.pop()
    147
    148
    149      ##
    150      # Create an Event section (can be opened/closed)
    151      # @param title title of the MainContent section
    152 -    def OpenEvent(self, title=""):
    153          self.__stack.append(self.__current_node)
    154          n = self.__doc.createElementNS("", "task")
    155          n.setAttributeNS("", "name", title)
    156          n.setAttributeNS("", "type", "event")
    157          n.setAttributeNS("", "time", datetime.datetime.now().ctime())
    158          self.__current_node.appendChild(n)
    159          self.__current_node = n
    160          if self.__verbose:
    161              print ("---------------------------------------------------------------------")
    162              print (" + %s" % title)
    163
    164 -    def SetCustomOutputer(self, type, classname, config = None):
    165          n = self.__doc.createElementNS("", "__customoutputer")
    166          n.setAttributeNS("", "type", type)
    167          n.setAttributeNS("", "module", classname)
    168          if config != None:
    169              n.appendChild(config)
    170          self.__lognode.appendChild(n)
    171
    172      ##
    173      # Close the current Event
    174      # Make sure you have closed other Event/Section first
    175 -    def CloseEvent(self):
    176          if self.__current_node.nodeName != "task" and (self.__current_node.attributes.has_key('type') and self.__current_node.attributes['type']=="event"):
    177              raise Exception("not closing a 'event' typed node")
    178          self.__current_node = self.__stack.pop()
    179
    180      ##
    181      # __getattribute__ has been overrided to enable dynamic messaging.
    182      # @param attr the name of the method (or attribute...)
    183 -    def __getattribute__(self, attr):
    184          try:
    185              return object.__getattribute__(self, attr)
    186          except AttributeError:
    187              return _CustomizePrint(self, attr)
    188
    189      ##
    190      # Generic method that handle the print in the XML document
    191      # @param kind type of output
    192      # @param *args a list of arguments (must be strings)
    193 -    def _print(self, kind, *args):
    194          output = u"".join(map(lambda x: u"%s" % x, list(*args)))
    195          nodetype = kind.lower()
    196          msgtype = ""
    197          if nodetype != "print" and nodetype != "info" and nodetype != "debug":
    198              msgtype = "%s:" % nodetype.upper()
    199          if self.__verbose:
    200              print "%s %s" % (msgtype, output.encode('utf-8'))
    201
    202
    203          n = self.__doc.createElementNS("", "message")
    204          n.setAttributeNS("", "priority", nodetype)
    205          #n.setAttributeNS("", "time", datetime.datetime.now().ctime())
    206          n.appendChild(self.__doc.createCDATASection(output))
    207          self.__current_node.appendChild(n)
    208  #        nodetype = kind.lower()
    209  #        if kind.lower() != "print" and kind.lower() != "printraw":
    210  #            nodename = kind.lower()
    211  #
    212  #        if nodename=="__print" and self.__current_node.lastChild!=None and self.__current_node.lastChild.nodeName  == nodename:
    213  #            self.__current_node.lastChild.appendChild(self.__doc.createTextNode("".join(*args).decode('iso-8859-1')))
    214  #        else:
    215  #            n = self.__doc.createElementNS("", nodename)
    216  #            n.setAttributeNS("", "step", "%d" % self.__step)
    217  #            self.__step += 1
    218  #            n.setAttributeNS("", "time", datetime.datetime.now().ctime())
    219  #            text_content = "".join(map(lambda x: str(x), list(*args))).decode('iso-8859-1')
    220  #            n.appendChild(self.__doc.createTextNode(text_content))
    221  #            self.__current_node.appendChild(n)
    222
    223
    224      ##
    225      #
    226 -    def SetFooterTitle(self, title):
    227          self.__footer.attributes['title'] = title
    228
    229 -    def SetFooterSubTitle(self, subtitle):
    230          self.__footer.attributes['subtitle'] = subtitle
    231
    232 -    def Die(self, title, subtitle, exception):
    233          self.SetFooterTitle(title)
    234          self.SetFooterSubTitle("%s\nException raised: %s\n%s" % (subtitle, exception, traceback.format_exc()))
    235
    236      ##
    237      # Write the DOM tree into a file.
    238      # @param filename the file to write in.
    239 -    def WriteToFile(self, filename):
    240          file_object = open(filename, "w")
    241          file_object.write(codecs.BOM_UTF8)
    242          file_object.write(self.__doc.toprettyxml(encoding = "utf-8"))
    243          file_object.close()
    244
    245
    246      ##
    247      # Write the DOM tree into a file.
    248      # @param filename the file to write in.
    249 -    def __str__(self):
    250          return self.__doc.toprettyxml(encoding="utf-8")
    251