Package nMOLDYN :: Package Core :: Module Logger |
[hide private]
[frames] | no frames]

# Source Code for Module nMOLDYN.Core.Logger

      1  """This module implements the classes used to handle the nMOLDYN logger.
      2
      3  Classes:
      4      * LogToGUI     : sets up a GUI logger.
      5      * LogToFile    : sets up a file logger.
      6      * LogToConsole : sets up a console logger.
      7
      8  Procedures:
      9      * LogMessage   : displays a logging message of a specified logging level to the specified logger(s).
     10  """
     11
     12  # The python distribution modules
     13  import logging
     14  import os
     15  from time import strftime
     16
     17  try:
     18      import Tkinter
     19      import tkMessageBox
     20  except:
     21      pass
     22
     23  LEVELS = {'debug': logging.DEBUG,\
     24            'info': logging.INFO,\
     25            'warning': logging.WARNING,\
     26            'error': logging.ERROR,\
     27            'critical': logging.CRITICAL}
     28
     29 -class LogToGUI(logging.Handler):
     30      """Sets up a GUI handler for the nMOLDYN logger.
     31
     32      Emits the logging messages to a Tk dialog.
     33      """
     34
     35 -    def __init__(self):
     36          """The constructor. Sets the logger."""
     37          logging.Handler.__init__(self)
     38          self.setFormatter(logging.Formatter('%(name)s %(levelname)s %(filename)s %(lineno)s \n%(message)s'))
     39
     40 -    def emit(self, record):
     41          """Emits the logging message in a tkMessageBox.
     42
     43          @param record: the logging message.
     44          @type record: instance of LogRecord class.
     45
     46          @note: the tkMessageBox called will depend on the logging level.
     47              - tkMessageBox.showerror for 'ERROR' and 'CRITICAL' logging levels.
     48              - tkMessageBox.showwarning for 'WARNING' logging level.
     49              - tkMessageBox.showinfo for other logging levels.
     50          """
     51
     52          if record.levelname in ['ERROR','CRITICAL']:
     53              tkMessageBox.showerror(record.levelname.capitalize(), self.format(record))
     54          elif record.levelname == 'WARNING':
     55              tkMessageBox.showwarning(record.levelname.capitalize(), self.format(record))
     56          else:
     57              tkMessageBox.showinfo(record.levelname.capitalize(), self.format(record))
     58
     59 -class LogToFile(logging.FileHandler):
     60      """Sets up a file logger.
     61
     62      Emits the logging messages to a file.
     63      """
     64
     65 -    def __init__(self, fileName):
     66          """The constructor. Sets the logger.
     67
     68          @param fileName: the name of the file where all the logging messages will be emitted.
     69          @type fileName: string
     70          """
     71          logging.FileHandler.__init__(self, fileName)
     72
     73      # The overdefined emit Handler method.
     74 -    def emit(self, record):
     75          """Emits the logging message in a file.
     76
     77          @param record: the logging message.
     78          @type record: instance of LogRecord class.
     79          """
     80          # If the record level is INFO then produce a slightly different output for the logfile.
     81          if record.levelname == 'INFO':
     82              self.setFormatter(logging.Formatter('%(name)s %(levelname)s ---> %(message)s'))
     83          elif record.levelname == 'WARNING':
     84              self.setFormatter(logging.Formatter('!'*119 + '\n%(name)s %(levelname)s ---> %(filename)s %(lineno)s %(message)s\n' + '!'*119))
     85          else:
     86              self.setFormatter(logging.Formatter('%(name)s %(levelname)s ---> %(filename)s %(lineno)s %(message)s'))
     87          # The formatted record is written to the log file.
     88          self.stream.write(self.format(record)+'\n')
     89          # And flushed.
     90          self.stream.flush()
     91
     92 -    def close(self):
     93          """Closes the file logger."""
     94          self.stream.close()
     95
     96 -class LogToConsole(logging.StreamHandler):
     97      """Sets up a console logger.
     98
     99      Emits the logging messages to the console.
    100      """
    101
    102 -    def __init__(self):
    103          """The constructor. Sets the logger."""
    104
    105          logging.StreamHandler.__init__(self)
    106
    107      # The overdefined emit Handler method.
    108 -    def emit(self, record):
    109          """Emits the logging message to the console.
    110
    111          @param record: the logging message.
    112          @type record: instance of LogRecord class.
    113          """
    114
    115          # If the record level is INFO then produce a slightly different output for the logfile.
    116          if record.levelname == 'INFO':
    117              self.setFormatter(logging.Formatter('%(name)s %(levelname)s ------> %(message)s'))
    118          elif record.levelname == 'WARNING':
    119              self.setFormatter(logging.Formatter('!'*119 + '\n%(name)s %(levelname)s ---> %(filename)s %(lineno)s %(message)s\n' + '!'*119))
    120          else:
    121              self.setFormatter(logging.Formatter('%(name)s %(levelname)s ---> %(filename)s %(lineno)s %(message)s'))
    122          # The formatted record is written to the console.
    123          self.stream.write(self.format(record)+'\n')
    124          # And flushed.
    125          self.stream.flush()
    126
    127 -def LogMessage(level = 'debug', message = '', media = ['gui','file','console']):
    128      """Displays the logging messahe |message| of logging level |level| to the logger(s) |media|.
    129
    130      @param level: a string being one of 'debug', 'info', 'warning', 'error' or 'critical' specifying
    131          the logging level of the logging message. Will change the way the logging message will be
    132          displayed.
    133      @type level: string
    134
    135      @param message: the logging message.
    136      @type message: string
    137
    138      @param media: a list containing 'gui' and/or 'file' and/or 'console' specifying on which logger(s) the logging
    139          message should emitted.
    140      @type media: list
    141      """
    142
    143      media = [s.lower() for s in media]
    144
    145      if 'console' in media:
    146          try:
    147              CONSOLE_LOGGER.log(LEVELS[level.lower()], message)
    148          except:
    149              pass
    150
    151      if 'file' in media:
    152          try:
    153              FILE_LOGGER.log(LEVELS[level.lower()], message)
    154          except:
    155              pass
    156
    157      if 'gui' in media:
    158          try:
    159              if Tkinter._default_root is not None:
    160                  GUI_LOGGER.log(LEVELS[level.lower()], message)
    161          except:
    162              pass
    163
    164  # The nMOLDYN file logger is set up.
    165  FILE_LOGGER = logging.getLogger('NMOLDYN LOGFILE')
    166  FILE_LOGGER.setLevel(logging.DEBUG)
    167
    168  # The nMOLDYN console logger is set up.
    169  CONSOLE_LOGGER = logging.getLogger('NMOLDYN CONSOLE')
    170  CONSOLE_LOGGER.setLevel(logging.INFO)
    171
    172  # The nMOLDYN GUI logger is set up.
    173  GUI_LOGGER = logging.getLogger('NMOLDYN GUI')
    174  GUI_LOGGER.setLevel(logging.INFO)
    175