Advertisement
Guest User

Untitled

a guest
May 2nd, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.77 KB | None | 0 0
  1. class FBLoggingHandler(logging.StreamHandler):
  2.     """
  3.    This creates a custom logging handler object that allows for re-directing
  4.    output to various locations.
  5.    """
  6.  
  7.     def __init__(self,
  8.                  widget=None,
  9.                  write_to_logfile=True,
  10.                  destFile=None,
  11.                  log_to_stdout=False,
  12.                  level=logging.INFO):
  13.         """
  14.        The constructor.
  15.  
  16.  
  17.        :param log_to_stdout: ``bool`` determining if logging output should be
  18.            redirected to ``stdout``. Defaults to ``False``.
  19.  
  20.        :param widget: ``QWidget`` to redirect logging output to. Must accept
  21.            text insertion method of some sort. Will be ignored if unspecified.
  22.  
  23.        :param write_to_logfile: ``bool`` determining if the output should be
  24.            written to a logfile. Defaults to ``True``.
  25.  
  26.        :param destFile: ``string`` that is path to the logfile to be written to on disk.
  27.            If no file is specified, one will be created based on the application name in
  28.            the user's ``HOME`` folder. Does nothing if ``write_to_logfile`` is set to
  29.            ``False``.
  30.  
  31.        :param level: ``logging.LEVEL`` that will be the logging level specified to be used
  32.            for writing to disk. Defaults to ``INFO`` level.
  33.  
  34.        :return: ``None``
  35.        """
  36.  
  37.         super(FBLoggingHandler, self).__init__()
  38.  
  39.         self.widget = widget
  40.         self.write_to_logfile = write_to_logfile
  41.  
  42.         if self.write_to_logfile:
  43.  
  44.             if destFile and os.path.isfile(destFile):
  45.                 self.destFile = destFile
  46.  
  47.             else:
  48.                 self.destFile = os.path.join(
  49.                     os.path.expanduser('~'),
  50.                     __organization__,
  51.                     __application__,
  52.                     'log.txt'
  53.                 )
  54.  
  55.         self.level = level
  56.  
  57.         # Set logging message output format
  58.         formatter = logging.Formatter('%(asctime)s - %(name)s - '
  59.                                       '%(levelname)s - %(message)s\n\n')
  60.         self.setFormatter(formatter)
  61.  
  62.  
  63.     def flush(self):
  64.         """
  65.        Overloads the base flush() method.
  66.        Does nothing for this handler.
  67.  
  68.        :return:
  69.        """
  70.         pass
  71.  
  72.  
  73.     def emit(self, record, write_mode='a+'):
  74.         """
  75.        Overloads the base emit() method.
  76.        Emits a record to log.
  77.  
  78.        :param write_mode: ``str`` that determines how the logfile is written to.
  79.            This follows the standard modes that any Python file object handle
  80.            has for writing data to.
  81.  
  82.        :param record: ``str`` message that will be written to log
  83.  
  84.        :return: ``str`` that is the logging output.
  85.        """
  86.         try:
  87.             msg = self.format(record)
  88.  
  89.             if self.write_to_logfile:
  90.  
  91.                 if not os.path.isfile(self.destFile):
  92.                     sys.stdout.write('\n\nExisting logfile not found, creating '
  93.                                      'default one...\n\n')
  94.                     os.makedirs(os.path.dirname(self.destFile))
  95.                     write_mode = 'w'
  96.  
  97.                 # Create logfile if it doesn't exist and append the logging info
  98.                 with open(self.destFile, mode=write_mode) as log_file:
  99.                     log_file.write(msg)
  100.  
  101.             if hasattr(self.widget, 'insertPlainText') and \
  102.                     hasattr(self.widget, 'moveCursor'):
  103.                 self.widget.moveCursor(QTextCursor.End)
  104.                 self.widget.insertPlainText(self.format(record))
  105.  
  106.             return msg
  107.  
  108.         except KeyboardInterrupt:
  109.             raise KeyboardInterrupt
  110.  
  111.         except SystemExit:
  112.             raise KeyboardInterrupt
  113.  
  114.         except Exception:
  115.             self.handleError(record)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement