Debug Tools
Debugger Class Reference
Inheritance diagram for Debugger:
Collaboration diagram for Debugger:

Public Member Functions

def __init__ (self, logger_name, logger_level=None)
 
def output_file (self)
 
def active (self)
 
def debug_level (self)
 
def debug_level (self, debug_level)
 
def traceback (self, kwargs)
 
def reset (self)
 
def setup_basic (self, kwargs)
 
def newline (self, debug_level=1, count=1)
 
def new_line (self, debug_level=1, count=1)
 
def __call__ (self, debug_level=1, msg=EMPTY_KWARG, args, kwargs)
 
def clean (self, debug_level=1, msg=EMPTY_KWARG, args, kwargs)
 
def basic (self, debug_level=1, msg=EMPTY_KWARG, args, kwargs)
 
def clear (self, delete=False)
 
def invert (self)
 
def handle_stderr (self, stderr=False, stdout=False)
 
def setup (self, file=EMPTY_KWARG, mode=EMPTY_KWARG, delete=EMPTY_KWARG, date=EMPTY_KWARG, levels=EMPTY_KWARG, function=EMPTY_KWARG, name=EMPTY_KWARG, time=EMPTY_KWARG, msecs=EMPTY_KWARG, tick=EMPTY_KWARG, separator=EMPTY_KWARG, formatter=EMPTY_KWARG, rotation=EMPTY_KWARG, kwargs)
 
def warn (self, msg, args, kwargs)
 
def exception (self, msg, args, kwargs)
 
def addHandler (self, handler)
 
def removeHandler (self, handler)
 
def deleteAllLoggers (cls)
 
def delete (self)
 
def removeHandlers (self)
 
def hasStreamHandlers (self)
 
def fix_children (self, callable_action)
 
def get_debug_file_path (cls, file_path)
 
def remove_windows_driver_letter (cls, file_path)
 
def getRootLogger (cls)
 
def __str__ (self)
 
def findCaller (self)
 
def findCaller (self, stack_info=False)
 
def makeRecord (self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None)
 
def makeRecord (self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None)
 

Static Public Member Functions

def getFormat (arguments, setting, default, next_parameter="")
 

Public Attributes

 trimname
 
 full_formatter
 
 clean_formatter
 
 basic_formatter
 
 debug_level
 
 clean
 
 basic
 

Detailed Description

    https://docs.python.org/2.6/library/logging.html

    How to define global function in Python?
    https://stackoverflow.com/questions/27930038/how-to-define-global-function-in-python

    How to print list inside python print?
    https://stackoverflow.com/questions/45427500/how-to-print-list-inside-python-print

Definition at line 130 of file logger.py.

Constructor & Destructor Documentation

◆ __init__()

def __init__ (   self,
  logger_name,
  logger_level = None 
)
    See the factory global function logger.getLogger().

Definition at line 144 of file logger.py.

References Debugger._debugger_level, Debugger._file, Debugger._force_debug, Debugger._frame_level, Debugger._last_tick, Debugger._reset(), Debugger._stream, and Debugger.trimname.

144  def __init__(self, logger_name, logger_level=None):
145  """
146  See the factory global function logger.getLogger().
147  """
148  # What is a clean, pythonic way to have multiple constructors in Python?
149  # https://stackoverflow.com/questions/682504/what-is-a-clean-pythonic-way-to-have-multiple-constructors-in-python
150  super( Debugger, self ).__init__( logger_name, logger_level or "DEBUG" )
151 
152  self._file = None
153  self._stream = None
154 
155  # Initialize the first last tick as the current tick
156  self._last_tick = timeit.default_timer()
157 
158  # Forces this debug_level into all children
159  self._force_debug = None
160  self.trimname = 0
161 
162  # Enable debug messages: (bitwise)
163  # 0 - Disabled debugging
164  # 1 - Errors messages
165  self._frame_level = 4
166  self._debugger_level = 127
167  self._reset()
168 
Here is the call graph for this function:

Member Function Documentation

◆ __call__()

def __call__ (   self,
  debug_level = 1,
  msg = EMPTY_KWARG,
  args,
  kwargs 
)
    Log to the current active handlers its message based on the bitwise `self._debugger_level`
    value. Note, differently from the standard logging level, each logger object has its own
    bitwise logging level, instead of all sharing the main `level`.

Definition at line 346 of file logger.py.

References Debugger._debugger_level, Debugger._log(), Debugger._log_clean(), Debugger.active(), and Debugger.clean_formatter.

346  def __call__(self, debug_level=1, msg=EMPTY_KWARG, *args, **kwargs):
347  """
348  Log to the current active handlers its message based on the bitwise `self._debugger_level`
349  value. Note, differently from the standard logging level, each logger object has its own
350  bitwise logging level, instead of all sharing the main `level`.
351  """
352 
353  if type( debug_level ) is int:
354 
355  if msg is EMPTY_KWARG:
356 
357  if self._debugger_level & 1 != 0:
358  kwargs['debug_level'] = 1
359  self._log( DEBUG, debug_level, args, **kwargs )
360 
361  elif self._debugger_level & debug_level != 0:
362  kwargs['debug_level'] = debug_level
363  self._log( DEBUG, msg, args, **kwargs )
364 
365  else:
366 
367  if self._debugger_level & 1 != 0:
368  kwargs['debug_level'] = 1
369 
370  if msg is EMPTY_KWARG:
371  self._log( DEBUG, debug_level, args, **kwargs )
372 
373  else:
374  self._log( DEBUG, debug_level, (msg,) + args, **kwargs )
375 
Here is the call graph for this function:

◆ active()

def active (   self)
    Works accordingly with super::hasHandlers(), except that this returns the activate
    logger object if it has some activate handler, or None if there are not loggers with
    active handlers.

    The root logger is not returned, unless it is already setup with handlers.

Definition at line 178 of file logger.py.

Referenced by Debugger.__call__(), Debugger.basic(), Debugger.clean(), Debugger.clear(), Debugger.debug_level(), Debugger.exception(), and Debugger.setup().

178  def active(self):
179  """
180  Works accordingly with super::hasHandlers(), except that this returns the activate
181  logger object if it has some activate handler, or None if there are not loggers with
182  active handlers.
183 
184  The root logger is not returned, unless it is already setup with handlers.
185  """
186  current = self
187 
188  while current:
189 
190  if current.handlers:
191  return current
192 
193  if not current.propagate:
194  break
195 
196  else:
197  current = current.parent
198 
199  return None
200 
Here is the caller graph for this function:

◆ addHandler()

def addHandler (   self,
  handler 
)
    Override the super() method to correctly set up `sys.stderr/stdout` handlers.

    When adding a new handler and either `sys.stderr` or `sys.stdout` is enabled. It is
    required to check whether there is also a stream handler enabled, and if so, then, we
    need to add a log record filter to avoid infinity log records trying to be displayed.
    See also logging::Logger::addHandler().

Definition at line 1071 of file logger.py.

References Debugger._file, Debugger._file_context_filter, Debugger._has_file_context_filter, Debugger._stderr(), Debugger._stdout(), Debugger._stream, and Debugger.handle_stderr().

Referenced by Debugger.setup().

1071  def addHandler(self, handler):
1072  """
1073  Override the super() method to correctly set up `sys.stderr/stdout` handlers.
1074 
1075  When adding a new handler and either `sys.stderr` or `sys.stdout` is enabled. It is
1076  required to check whether there is also a stream handler enabled, and if so, then, we
1077  need to add a log record filter to avoid infinity log records trying to be displayed.
1078  See also logging::Logger::addHandler().
1079  """
1080 
1081  if self._stderr or self._stdout:
1082 
1083  if self._file and self._stream:
1084  handler.addFilter( self._file_context_filter )
1085 
1086  self._has_file_context_filter = True
1087  _acquireLock()
1088 
1089  try:
1090  for other_handler in self.handlers:
1091  other_handler.addFilter( self._file_context_filter )
1092 
1093  finally:
1094  _releaseLock()
1095 
1096  self.handle_stderr( self._stderr, self._stdout )
1097 
1098  # else: # TODO: Support other this logic also for other handlers and the builtin _stream and _file
1099 
1100  super( Debugger, self ).addHandler( handler )
1101 
Here is the call graph for this function:
Here is the caller graph for this function:

◆ basic()

def basic (   self,
  debug_level = 1,
  msg = EMPTY_KWARG,
  args,
  kwargs 
)
    Prints the bitwise logging message with the standard basic formatter, which uses by
    default the format: [%(name)s] %(asctime)s:%(msecs)010.6f %(tickDifference).2e %(message)s

    The basic logger format can be configured setting the standard formatter with
    setup() and calling invert() to set the `full_formatter` as
    the basic formatter.

Definition at line 510 of file logger.py.

References Debugger._debugger_level, Debugger._log(), Debugger.active(), and Debugger.basic_formatter.

510  def basic(self, debug_level=1, msg=EMPTY_KWARG, *args, **kwargs):
511  """
512  Prints the bitwise logging message with the standard basic formatter, which uses by
513  default the format: [%(name)s] %(asctime)s:%(msecs)010.6f %(tickDifference).2e %(message)s
514 
515  The basic logger format can be configured setting the standard formatter with
516  setup() and calling invert() to set the `full_formatter` as
517  the basic formatter.
518  """
519 
520  if type( debug_level ) is int:
521 
522  if msg is EMPTY_KWARG:
523 
524  if self._debugger_level & 1 != 0:
525  other = self.active or self
526 
527  old_formatters = {}
528  _acquireLock()
529  try:
530  for handler in other.handlers:
531  old_formatters[handler] = handler.formatter
532  handler.formatter = self.basic_formatter
533 
534  finally:
535  _releaseLock()
536 
537  kwargs['debug_level'] = 1
538  self._log( DEBUG, debug_level, args, **kwargs )
539 
540  for handler, formatter in old_formatters.items():
541  handler.formatter = formatter
542 
543  elif self._debugger_level & debug_level != 0:
544  other = self.active or self
545 
546  old_formatters = {}
547  _acquireLock()
548  try:
549  for handler in other.handlers:
550  old_formatters[handler] = handler.formatter
551  handler.formatter = self.basic_formatter
552 
553  finally:
554  _releaseLock()
555 
556  kwargs['debug_level'] = debug_level
557  self._log( DEBUG, msg, args, **kwargs )
558 
559  for handler, formatter in old_formatters.items():
560  handler.formatter = formatter
561 
562  else:
563 
564  if self._debugger_level & 1 != 0:
565 
566  if msg is EMPTY_KWARG:
567  other = self.active or self
568 
569  old_formatters = {}
570  _acquireLock()
571  try:
572  for handler in other.handlers:
573  old_formatters[handler] = handler.formatter
574  handler.formatter = self.basic_formatter
575 
576  finally:
577  _releaseLock()
578 
579  kwargs['debug_level'] = 1
580  self._log( DEBUG, debug_level, args, **kwargs )
581 
582  for handler, formatter in old_formatters.items():
583  handler.formatter = formatter
584 
585  else:
586  other = self.active or self
587 
588  old_formatters = {}
589  _acquireLock()
590  try:
591  for handler in other.handlers:
592  old_formatters[handler] = handler.formatter
593  handler.formatter = self.basic_formatter
594 
595  finally:
596  _releaseLock()
597 
598  kwargs['debug_level'] = 1
599  self._log( DEBUG, debug_level, (msg,) + args, **kwargs )
600 
601  for handler, formatter in old_formatters.items():
602  handler.formatter = formatter
603 
Here is the call graph for this function:

◆ clean()

def clean (   self,
  debug_level = 1,
  msg = EMPTY_KWARG,
  args,
  kwargs 
)
    Prints a message without the time prefix as `[plugin_name.py] 11:13:51:0582059`

    How to insert newline in python logging?
    https://stackoverflow.com/questions/20111758/how-to-insert-newline-in-python-logging

Definition at line 397 of file logger.py.

References Debugger._debugger_level, Debugger._log(), Debugger._log_clean(), Debugger.active(), Debugger.basic_formatter, and Debugger.clean_formatter.

397  def clean(self, debug_level=1, msg=EMPTY_KWARG, *args, **kwargs):
398  """
399  Prints a message without the time prefix as `[plugin_name.py] 11:13:51:0582059`
400 
401  How to insert newline in python logging?
402  https://stackoverflow.com/questions/20111758/how-to-insert-newline-in-python-logging
403  """
404 
405  if type( debug_level ) is int:
406 
407  if msg is EMPTY_KWARG:
408 
409  if self._debugger_level & 1 != 0:
410  other = self.active or self
411 
412  old_formatters = {}
413  _acquireLock()
414  try:
415  for handler in other.handlers:
416  old_formatters[handler] = handler.formatter
417  handler.formatter = self.clean_formatter
418 
419  finally:
420  _releaseLock()
421 
422  kwargs['debug_level'] = 1
423  self._log_clean( debug_level, args, kwargs )
424 
425  for handler, formatter in old_formatters.items():
426  handler.formatter = formatter
427 
428  elif self._debugger_level & debug_level != 0:
429  other = self.active or self
430 
431  old_formatters = {}
432  _acquireLock()
433  try:
434  for handler in other.handlers:
435  old_formatters[handler] = handler.formatter
436  handler.formatter = self.clean_formatter
437 
438  finally:
439  _releaseLock()
440 
441  kwargs['debug_level'] = debug_level
442  self._log_clean( msg, args, kwargs )
443 
444  for handler, formatter in old_formatters.items():
445  handler.formatter = formatter
446 
447  else:
448 
449  if self._debugger_level & 1 != 0:
450 
451  if msg is EMPTY_KWARG:
452  other = self.active or self
453 
454  old_formatters = {}
455  _acquireLock()
456  try:
457  for handler in other.handlers:
458  old_formatters[handler] = handler.formatter
459  handler.formatter = self.clean_formatter
460 
461  finally:
462  _releaseLock()
463 
464  kwargs['debug_level'] = 1
465  self._log_clean( debug_level, args, kwargs )
466 
467  for handler, formatter in old_formatters.items():
468  handler.formatter = formatter
469 
470  else:
471  other = self.active or self
472 
473  old_formatters = {}
474  _acquireLock()
475  try:
476  for handler in other.handlers:
477  old_formatters[handler] = handler.formatter
478  handler.formatter = self.clean_formatter
479 
480  finally:
481  _releaseLock()
482 
483  kwargs['debug_level'] = 1
484  self._log_clean( debug_level, (msg,) + args, kwargs )
485 
486  for handler, formatter in old_formatters.items():
487  handler.formatter = formatter
488 
Here is the call graph for this function:

◆ clear()

def clear (   self,
  delete = False 
)
    Clear the log file contents.

    @param `delete` if True, the log file will also be removed/deleted and the current file
handler will be removed.

Definition at line 607 of file logger.py.

References Debugger._stderr(), Debugger._stdout(), Debugger.active(), Debugger.handle_stderr(), and CleanLogRecord.name.

Referenced by SleepEvent.sleep().

607  def clear(self, delete=False):
608  """
609  Clear the log file contents.
610 
611  @param `delete` if True, the log file will also be removed/deleted and the current file
612  handler will be removed.
613  """
614  active = self.active
615 
616  if active and active.output_file:
617  output_file = active.output_file
618  sys.stderr.write( "Cleaning %s (delete=%s) the file: %s\n" % ( self.name, delete, output_file ) )
619 
620  active._create_file( output_file, active._arguments['rotation'], active._arguments['mode'], True, delete )
621  self.handle_stderr( stderr=self._stderr and not delete, stdout=self._stdout and not delete )
622 
Here is the call graph for this function:
Here is the caller graph for this function:

◆ debug_level() [1/2]

def debug_level (   self)
    Return this logger active debug level.

Definition at line 202 of file logger.py.

References Debugger._debugger_level.

202  def debug_level(self):
203  """
204  Return this logger active debug level.
205  """
206  return self._debugger_level
207 

◆ debug_level() [2/2]

def debug_level (   self,
  debug_level 
)
    Set this current logger object active debug level.

Definition at line 209 of file logger.py.

References Debugger._arguments, Debugger._debugger_level, and Debugger.active().

209  def debug_level(self, debug_level):
210  """
211  Set this current logger object active debug level.
212  """
213 
214  if isinstance( debug_level, int ):
215  self._debugger_level = debug_level
216 
217  else:
218  raise ValueError( "Error: The debug_level `%s` must be an integer!" % debug_level )
219 
Here is the call graph for this function:

◆ deleteAllLoggers()

def deleteAllLoggers (   cls)
    Delete all loggers created by `getLogger()` calls.

Definition at line 1132 of file logger.py.

References Debugger.exception(), CleanLogRecord.name, and Debugger.removeHandlers().

1132  def deleteAllLoggers(cls):
1133  """
1134  Delete all loggers created by `getLogger()` calls.
1135  """
1136  _acquireLock()
1137 
1138  try:
1139  cls.manager.loggerDict.clear()
1140 
1141  except Exception:
1142  cls.exception("Could not delete all registered loggers!")
1143 
1144  finally:
1145  _releaseLock()
1146 
Here is the call graph for this function:

◆ exception()

def exception (   self,
  msg,
  args,
  kwargs 
)
    Fix second indirection created by the super().error() method, by directly calling _log()

Definition at line 923 of file logger.py.

References Debugger._arguments, Debugger._create_formatter(), Debugger._current_tick, Debugger._last_tick, Debugger._log(), Debugger.active(), Debugger.getFormat(), and CleanLogRecord.name.

Referenced by Debugger.deleteAllLoggers(), Debugger.handle_stderr(), and Debugger.setup().

923  def exception(self, msg, *args, **kwargs):
924  """
925  Fix second indirection created by the super().error() method, by directly calling _log()
926  """
927  if self.isEnabledFor(ERROR):
928  self._log(ERROR, msg, args, exc_info=True, **kwargs)
929 
Here is the call graph for this function:
Here is the caller graph for this function:

◆ fix_children()

def fix_children (   self,
  callable_action 
)
    When automatically creating loggers, some children logger can be setup before the
    parent logger, if the children logger is instantiated on module level and its module
    is imported before the parent logger to be setup.

    Then this will cause the the both parent and child logger to be setup and have handlers
    outputting data to theirs output stream. Hence, here we fix that by disabling the
    children logger when they are setup before the parent logger.

    This method is only called automatically by this module level function `getLogger()`
    when is set to automatically setup the logger. If you are not using the automatic setup
    you do not need to use this function because you should know what you are doing and how
    you should setup your own loggers.

Definition at line 1184 of file logger.py.

References CleanLogRecord.name.

1184  def fix_children(self, callable_action):
1185  """
1186  When automatically creating loggers, some children logger can be setup before the
1187  parent logger, if the children logger is instantiated on module level and its module
1188  is imported before the parent logger to be setup.
1189 
1190  Then this will cause the the both parent and child logger to be setup and have handlers
1191  outputting data to theirs output stream. Hence, here we fix that by disabling the
1192  children logger when they are setup before the parent logger.
1193 
1194  This method is only called automatically by this module level function `getLogger()`
1195  when is set to automatically setup the logger. If you are not using the automatic setup
1196  you do not need to use this function because you should know what you are doing and how
1197  you should setup your own loggers.
1198  """
1199  loggers = Debugger.manager.loggerDict
1200  parent_name = self.name
1201  parent_name_length = len( parent_name )
1202 
1203  for logger_name in loggers:
1204  logger = loggers[logger_name]
1205 
1206  if not isinstance( logger, PlaceHolder ):
1207 
1208  # i.e., if logger.parent.name.startswith( parent_name )
1209  if logger.parent.name[:parent_name_length] == parent_name:
1210  callable_action( logger )
1211 

◆ get_debug_file_path()

def get_debug_file_path (   cls,
  file_path 
)
    Reliably detect Windows in Python
    https://stackoverflow.com/questions/1387222/reliably-detect-windows-in-python

    Convert "D:/User/Downloads/debug.txt"
    To "/cygwin/D/User/Downloads/debug.txt"
    To "/mnt/D/User/Downloads/debug.txt"

Definition at line 1213 of file logger.py.

References Debugger.remove_windows_driver_letter().

Referenced by Debugger.setup().

1213  def get_debug_file_path(cls, file_path):
1214  """
1215  Reliably detect Windows in Python
1216  https://stackoverflow.com/questions/1387222/reliably-detect-windows-in-python
1217 
1218  Convert "D:/User/Downloads/debug.txt"
1219  To "/cygwin/D/User/Downloads/debug.txt"
1220  To "/mnt/D/User/Downloads/debug.txt"
1221  """
1222  is_absolute = os.path.isabs( file_path )
1223  platform_info = platform.platform( True ).lower()
1224 
1225  if is_absolute \
1226  and not file_path.startswith( "/cygdrive/" ) \
1227  and "cygwin" in platform_info:
1228 
1229  new_output = "/cygdrive/" + cls.remove_windows_driver_letter( file_path )
1230 
1231  elif is_absolute \
1232  and not file_path.startswith( "/mnt/" ) \
1233  and "linux" in platform_info \
1234  and "microsoft" in platform_info:
1235 
1236  new_output = cls.remove_windows_driver_letter( file_path )
1237  new_output = "/mnt/" + new_output[0].lower() + new_output[1:]
1238 
1239  else:
1240  new_output = os.path.abspath( file_path )
1241 
1242  # print( "Debugger, is_absolute: %s" % is_absolute )
1243  # print( "Debugger, new_output: %s" % new_output )
1244  # print( "Debugger, isabs: %s" % str( os.path.isabs( new_output ) ) )
1245  # print( "Debugger, platform_info: %s" % platform_info )
1246  return new_output
1247 
Here is the call graph for this function:
Here is the caller graph for this function:

◆ getRootLogger()

def getRootLogger (   cls)
    Return the main root logger `root_debugger` used by this extension of the standard
    logging module.

Definition at line 1255 of file logger.py.

References Debugger._frame_level.

1255  def getRootLogger(cls):
1256  """
1257  Return the main root logger `root_debugger` used by this extension of the standard
1258  logging module.
1259  """
1260  return cls.root
1261 

◆ handle_stderr()

def handle_stderr (   self,
  stderr = False,
  stdout = False 
)
    Register a exception hook if the logger is capable of logging them to alternate streams.

    @param `stderr` if True, it will enable the logging hook on the sys.stderr.
    @param `stdout` if True, it will enable the logging hook on the sys.stdout.

Definition at line 629 of file logger.py.

References Debugger._debug_level, Debugger._debugme, Debugger._file, Debugger._stream, Debugger.debug_level, Debugger.exception(), Debugger.handle_stderr(), Debugger.hasStreamHandlers(), CleanLogRecord.name, Debugger.removeHandler(), and Debugger.setup().

Referenced by Debugger.addHandler(), Debugger.clear(), Debugger.handle_stderr(), and Debugger.removeHandler().

629  def handle_stderr(self, stderr=False, stdout=False):
630  """
631  Register a exception hook if the logger is capable of logging them to alternate streams.
632 
633  @param `stderr` if True, it will enable the logging hook on the sys.stderr.
634  @param `stdout` if True, it will enable the logging hook on the sys.stdout.
635  """
636  _acquireLock()
637 
638  try:
639  if self._debugme:
640  sys.stderr.write( "stderr: %s, stdout: %s" % ( stderr, stdout ) )
641  sys.stderr.write( "sys.stderr: %s, sys.stdout: %s" % ( sys.stderr, sys.stdout ) )
642  sys.stderr.write( "name: %s, hasStreamHandlers: %s" % ( self.name, self.hasStreamHandlers() ) )
643 
644  if stderr:
645  stderr_replacement.lock( self )
646  else:
647  stderr_replacement.unlock()
648 
649  if stdout:
650  stdout_replacement.lock( self )
651  else:
652  stdout_replacement.unlock()
653 
654  except Exception:
655  self.exception( "Could not register the sys.stderr stream handler" )
656 
657  finally:
658  _releaseLock()
659 
Here is the call graph for this function:
Here is the caller graph for this function:

◆ hasStreamHandlers()

def hasStreamHandlers (   self)
    Return True if the current logger has some stream handler defined.

Definition at line 1171 of file logger.py.

Referenced by Debugger.handle_stderr().

1171  def hasStreamHandlers(self):
1172  """
1173  Return True if the current logger has some stream handler defined.
1174  """
1175 
1176  for handler in self.handlers:
1177  # print( "Name: %s, handler: %s" % ( self.name, type( handler ) ) )
1178 
1179  if "StreamHandler" in str( type( handler ) ):
1180  return True
1181 
1182  return False
1183 
Here is the caller graph for this function:

◆ invert()

def invert (   self)
    Inverts the default formatter between the preconfigured `basic` and `full_formatter`.

Definition at line 623 of file logger.py.

References Debugger.basic_formatter, and Debugger.full_formatter.

623  def invert(self):
624  """
625  Inverts the default formatter between the preconfigured `basic` and `full_formatter`.
626  """
627  self.basic_formatter, self.full_formatter = self.full_formatter, self.basic_formatter
628 

◆ makeRecord() [1/2]

def makeRecord (   self,
  name,
  level,
  fn,
  lno,
  msg,
  args,
  exc_info,
  func = None,
  extra = None 
)
A factory method which can be overridden in subclasses to create
specialized LogRecords.

Definition at line 1360 of file logger.py.

References Debugger.trimname.

Referenced by Debugger.makeRecord().

1360  def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None):
1361  """
1362  A factory method which can be overridden in subclasses to create
1363  specialized LogRecords.
1364  """
1365  rv = SmartLogRecord(name[self.trimname:], level, fn, lno, msg, args, exc_info, func)
1366  if extra is not None:
1367  for key in extra:
1368  if (key in ["message", "asctime"]) or (key in rv.__dict__):
1369  raise KeyError("Attempt to overwrite %r in LogRecord" % key)
1370  rv.__dict__[key] = extra[key]
1371  return rv
1372 
Here is the caller graph for this function:

◆ makeRecord() [2/2]

def makeRecord (   self,
  name,
  level,
  fn,
  lno,
  msg,
  args,
  exc_info,
  func = None,
  extra = None,
  sinfo = None 
)
A factory method which can be overridden in subclasses to create
specialized LogRecords.

Definition at line 1375 of file logger.py.

References Debugger.makeRecord(), and Debugger.trimname.

1375  def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None):
1376  """
1377  A factory method which can be overridden in subclasses to create
1378  specialized LogRecords.
1379  """
1380  rv = SmartLogRecord(name[self.trimname:], level, fn, lno, msg, args, exc_info, func, sinfo)
1381  if extra is not None:
1382  for key in extra:
1383  if (key in ["message", "asctime"]) or (key in rv.__dict__):
1384  raise KeyError("Attempt to overwrite %r in LogRecord" % key)
1385  rv.__dict__[key] = extra[key]
1386  return rv
1387 
1388 
Here is the call graph for this function:

◆ new_line()

def new_line (   self,
  debug_level = 1,
  count = 1 
)
    Prints a clean new line, without any formatter header.
    @param `count` how many new lines to output

Definition at line 338 of file logger.py.

References Debugger.clean.

338  def new_line(self, debug_level=1, count=1):
339  """
340  Prints a clean new line, without any formatter header.
341  @param `count` how many new lines to output
342  """
343  for index in range(count):
344  self.clean( debug_level, "" )
345 

◆ newline()

def newline (   self,
  debug_level = 1,
  count = 1 
)
    Prints a clean new line, without any formatter header.
    @param `count` how many new lines to output

Definition at line 330 of file logger.py.

References Debugger.clean.

330  def newline(self, debug_level=1, count=1):
331  """
332  Prints a clean new line, without any formatter header.
333  @param `count` how many new lines to output
334  """
335  for index in range(count):
336  self.clean( debug_level, "" )
337 

◆ removeHandler()

def removeHandler (   self,
  handler 
)
    Override the super() method to correctly set up `sys.stderr/stdout` handlers.

    When
    See also logging::Logger::removeHandler().

Definition at line 1102 of file logger.py.

References Debugger._file, Debugger._file_context_filter, Debugger._has_file_context_filter, Debugger._stderr(), Debugger._stdout(), Debugger._stream, and Debugger.handle_stderr().

Referenced by Debugger.handle_stderr(), and Debugger.removeHandlers().

1102  def removeHandler(self, handler):
1103  """
1104  Override the super() method to correctly set up `sys.stderr/stdout` handlers.
1105 
1106  When
1107  See also logging::Logger::removeHandler().
1108  """
1109 
1110  if self._has_file_context_filter:
1111 
1112  if not self._stderr and not self._stdout or not self._file or not self._stream:
1113  handler.removeFilter( self._file_context_filter )
1114 
1115  self._has_file_context_filter = False
1116  _acquireLock()
1117 
1118  try:
1119  for other_handler in self.handlers:
1120  other_handler.removeFilter( self._file_context_filter )
1121 
1122  finally:
1123  _releaseLock()
1124 
1125  self.handle_stderr( self._stderr, self._stdout )
1126 
1127  # else: # TODO: Support other this logic also for other handlers and the builtin _stream and _file
1128 
1129  super( Debugger, self ).removeHandler( handler )
1130 
Here is the call graph for this function:
Here is the caller graph for this function:

◆ removeHandlers()

def removeHandlers (   self)
    Delete all handlers registered to the current logger.

Definition at line 1161 of file logger.py.

References Debugger._debugme, Debugger._disable(), CleanLogRecord.name, and Debugger.removeHandler().

Referenced by Debugger.deleteAllLoggers(), and Debugger.reset().

1161  def removeHandlers(self):
1162  """
1163  Delete all handlers registered to the current logger.
1164  """
1165  if self._debugme: sys.stderr.write( "Removing all handlers from %s...\n" % self.name )
1166  self._disable( stream=True, file=True )
1167 
1168  for handler in self.handlers:
1169  self.removeHandler( handler )
1170 
Here is the call graph for this function:
Here is the caller graph for this function:

◆ reset()

def reset (   self)
    Reset all remembered parameters values set on the subsequent calls to `setup()`.

    Call this if you want to reset to remove all handlers and set all parameters values to
    their default.

Definition at line 280 of file logger.py.

References Debugger._arguments, Debugger._formatter_arguments(), Debugger._reset(), Debugger._setup_formatter(), Debugger.clean_formatter, Debugger.full_formatter, Debugger.removeHandlers(), and Debugger.setup_basic().

280  def reset(self):
281  """
282  Reset all remembered parameters values set on the subsequent calls to `setup()`.
283 
284  Call this if you want to reset to remove all handlers and set all parameters values to
285  their default.
286  """
287  self.removeHandlers()
288  self._reset()
289 
Here is the call graph for this function:

◆ setup()

def setup (   self,
  file = EMPTY_KWARG,
  mode = EMPTY_KWARG,
  delete = EMPTY_KWARG,
  date = EMPTY_KWARG,
  levels = EMPTY_KWARG,
  function = EMPTY_KWARG,
  name = EMPTY_KWARG,
  time = EMPTY_KWARG,
  msecs = EMPTY_KWARG,
  tick = EMPTY_KWARG,
  separator = EMPTY_KWARG,
  formatter = EMPTY_KWARG,
  rotation = EMPTY_KWARG,
  kwargs 
)
    If `file` parameter is passed, instead of output the debug to the standard output
    stream, send it to a file on the file system, which is faster for large outputs.

    As this function remembers most of its parameters passed from previous calls, you need to
    explicitly pass `file=None` with `delete=True` if you want to disable the file
    system output after setting up it to log to a file. See the function Debugger::reset()
    for the default parameters values used on this setup utility.

    If the parameters `date`, `levels`, `function`, `name`, `time`, `tick` and `msecs` are
    nonempty strings, their value will be used to defining their configuration formatting.
    For example, if you pass name="%(name)s: " the function name will be displayed as
    `name: `, instead of the default `[name] `.

    If you change your `sys.stderr` after creating an StreamHandler, you need to pass `handlers=True`
    to make it to recreate the StreamHandler because of the old reference to `sys.stderr`.

    Single page cheat-sheet about Python string formatting pyformat.info
    https://github.com/ulope/pyformat.info

    Override a method at instance level
    https://stackoverflow.com/questions/394770/override-a-method-at-instance-level

    @param `file`       a relative or absolute path to the log file. If empty the output
                will be sent to the standard output stream.

    @param `mode`       the file write mode on the file system (default `a`). It can be `a`
                to append to the existent file, or `w` to erase the existent file
                before start. If the parameter `rotation` is set to non zero, then
                this will be an integer value setting how many backups are going to
                be keep when doing the file rotation as specified on
                logging::handlers::RotatingFileHandler documentation.

    @param `delete`     if True (default False), it will delete the other handler before
                activate the current one, otherwise it will only activate the
                selected handler. Useful for enabling multiple handlers
                simultaneously.

    @param `date`       if True, add to the `full_formatter` the date on the format `%Y-%m-%d`.
    @param `levels`      if True, add to the `full_formatter` the log levels.
    @param `function`   if True, add to the `full_formatter` the function name.
    @param `name`       if True, add to the `full_formatter` the logger name.
    @param `time`       if True, add to the `full_formatter` the time on the format `%H:%M:%S:milliseconds.microseconds`.
    @param `msecs`      if True, add to the `full_formatter` the current milliseconds on the format ddd,ddddd.
    @param `tick`       if True, add to the `full_formatter` the time.perf_counter() difference from the last call.
    @param `separator`  if True, add to the `full_formatter` the a ` - ` to the end of the log record header.
    @param `formatter`  if not None, replace this `full_formatter` by the logging.Formatter() provided.

    @param `rotation`   if non zero, creates a RotatingFileHandler with the specified size
                in Mega Bytes instead of FileHandler when creating a log file by the
                `file` option. See logging::handlers::RotatingFileHandler for more
                information. See the parameter `mode` to specify how many files at
                most should be created by the rotation algorithm.

    @param `handlers`   if True (default False), it will force to create the handlers,
                even if there are no changes on the current saved default parameters.
                Its value is not saved between calls to this setup().

    @param `stderr`     if True (default True), it will install a listener to the `sys.stderr`
                console output. This is useful for logging not handled exceptions.

    @param `stdout`     if True (default False), it will install a listener to the `sys.stdout`
                console output. This is useful for logging all console output to a file.

    @param `force`      if an integer, set the `debug_level` into all created loggers hierarchy.
                Its value is not saved between calls to this setup().

    @param `active`     if True (default True), it will search for any other active logger in
                the current logger hierarchy and do the setup call on him. If no active
                logger is found, it will do the setup on the current logger object,
                Its value is not saved between calls to this setup().

    @param `fast`       if True (default False), it will disabled support to log message
                calls as `log('message')` and `log(333)`, and it force all log
                message calls to respect the format `log(1, message)`. This tradeoff
                gains dropping from about 10 seconds to about 7 seconds each
                10.000.000 log calls, when the logging debug level is set as
                disabled.

    @param `stream`     (default sys.stderr), an file like object to the StreamHandler use
                to print things when outputting results.

    @param `trimname` (default 0), Remove these nth characters from the logger name
                while creating the log record to print on the screen. Useful to keep
                several loggers grouped together but hide their parent.

Definition at line 703 of file logger.py.

References Debugger.__class__, Debugger._arguments, Debugger._configure_force(), Debugger._create_file(), Debugger._disable(), Debugger._fast_basic(), Debugger._fast_clean(), Debugger._file, Debugger._get_time_prefix(), Debugger._old_basic, Debugger._old_clean, Debugger._setup(), Debugger._setup_fast_loggers(), Debugger._stream, Debugger.active(), Debugger.addHandler(), Debugger.basic, Debugger.clean, Debugger.exception(), Debugger.full_formatter, Debugger.get_debug_file_path(), and Debugger.trimname.

Referenced by Debugger.handle_stderr().

703  separator=EMPTY_KWARG, formatter=EMPTY_KWARG, rotation=EMPTY_KWARG, **kwargs):
704  """
705  If `file` parameter is passed, instead of output the debug to the standard output
706  stream, send it to a file on the file system, which is faster for large outputs.
707 
708  As this function remembers most of its parameters passed from previous calls, you need to
709  explicitly pass `file=None` with `delete=True` if you want to disable the file
710  system output after setting up it to log to a file. See the function Debugger::reset()
711  for the default parameters values used on this setup utility.
712 
713  If the parameters `date`, `levels`, `function`, `name`, `time`, `tick` and `msecs` are
714  nonempty strings, their value will be used to defining their configuration formatting.
715  For example, if you pass name="%(name)s: " the function name will be displayed as
716  `name: `, instead of the default `[name] `.
717 
718  If you change your `sys.stderr` after creating an StreamHandler, you need to pass `handlers=True`
719  to make it to recreate the StreamHandler because of the old reference to `sys.stderr`.
720 
721  Single page cheat-sheet about Python string formatting pyformat.info
722  https://github.com/ulope/pyformat.info
723 
724  Override a method at instance level
725  https://stackoverflow.com/questions/394770/override-a-method-at-instance-level
726 
727  @param `file` a relative or absolute path to the log file. If empty the output
728  will be sent to the standard output stream.
729 
730  @param `mode` the file write mode on the file system (default `a`). It can be `a`
731  to append to the existent file, or `w` to erase the existent file
732  before start. If the parameter `rotation` is set to non zero, then
733  this will be an integer value setting how many backups are going to
734  be keep when doing the file rotation as specified on
735  logging::handlers::RotatingFileHandler documentation.
736 
737  @param `delete` if True (default False), it will delete the other handler before
738  activate the current one, otherwise it will only activate the
739  selected handler. Useful for enabling multiple handlers
740  simultaneously.
741 
742  @param `date` if True, add to the `full_formatter` the date on the format `%Y-%m-%d`.
743  @param `levels` if True, add to the `full_formatter` the log levels.
744  @param `function` if True, add to the `full_formatter` the function name.
745  @param `name` if True, add to the `full_formatter` the logger name.
746  @param `time` if True, add to the `full_formatter` the time on the format `%H:%M:%S:milliseconds.microseconds`.
747  @param `msecs` if True, add to the `full_formatter` the current milliseconds on the format ddd,ddddd.
748  @param `tick` if True, add to the `full_formatter` the time.perf_counter() difference from the last call.
749  @param `separator` if True, add to the `full_formatter` the a ` - ` to the end of the log record header.
750  @param `formatter` if not None, replace this `full_formatter` by the logging.Formatter() provided.
751 
752  @param `rotation` if non zero, creates a RotatingFileHandler with the specified size
753  in Mega Bytes instead of FileHandler when creating a log file by the
754  `file` option. See logging::handlers::RotatingFileHandler for more
755  information. See the parameter `mode` to specify how many files at
756  most should be created by the rotation algorithm.
757 
758  @param `handlers` if True (default False), it will force to create the handlers,
759  even if there are no changes on the current saved default parameters.
760  Its value is not saved between calls to this setup().
761 
762  @param `stderr` if True (default True), it will install a listener to the `sys.stderr`
763  console output. This is useful for logging not handled exceptions.
764 
765  @param `stdout` if True (default False), it will install a listener to the `sys.stdout`
766  console output. This is useful for logging all console output to a file.
767 
768  @param `force` if an integer, set the `debug_level` into all created loggers hierarchy.
769  Its value is not saved between calls to this setup().
770 
771  @param `active` if True (default True), it will search for any other active logger in
772  the current logger hierarchy and do the setup call on him. If no active
773  logger is found, it will do the setup on the current logger object,
774  Its value is not saved between calls to this setup().
775 
776  @param `fast` if True (default False), it will disabled support to log message
777  calls as `log('message')` and `log(333)`, and it force all log
778  message calls to respect the format `log(1, message)`. This tradeoff
779  gains dropping from about 10 seconds to about 7 seconds each
780  10.000.000 log calls, when the logging debug level is set as
781  disabled.
782 
783  @param `stream` (default sys.stderr), an file like object to the StreamHandler use
784  to print things when outputting results.
785 
786  @param `trimname` (default 0), Remove these nth characters from the logger name
787  while creating the log record to print on the screen. Useful to keep
788  several loggers grouped together but hide their parent.
789  """
790  self._setup( file=file, mode=mode, delete=delete, date=date, levels=levels,
791  function=function, name=name, time=time, msecs=msecs, tick=tick,
792  separator=separator, formatter=formatter, rotation=rotation, **kwargs )
793 
Here is the call graph for this function:
Here is the caller graph for this function:

◆ setup_basic()

def setup_basic (   self,
  kwargs 
)
    Configure the `basic_formatter` used by `basic()` logging function.

    @param `**kwargs` the same formatting arguments passed to `setup()`

Definition at line 297 of file logger.py.

References Debugger._formatter_arguments(), Debugger._setup_formatter(), and Debugger.basic_formatter.

Referenced by Debugger.reset().

297  def setup_basic(self, **kwargs):
298  """
299  Configure the `basic_formatter` used by `basic()` logging function.
300 
301  @param `**kwargs` the same formatting arguments passed to `setup()`
302  """
303  basic_arguments = self._formatter_arguments()
304  basic_arguments.update( kwargs )
305  self.basic_formatter = self._setup_formatter( basic_arguments )
306 
Here is the call graph for this function:
Here is the caller graph for this function:

◆ traceback()

def traceback (   self,
  kwargs 
)
    Prints the stack trace (traceback) until the current function call.

Definition at line 273 of file logger.py.

References Debugger._log().

273  def traceback(self, **kwargs):
274  """
275  Prints the stack trace (traceback) until the current function call.
276  """
277  kwargs['debug_level'] = 1
278  self._log( DEBUG, "traceback.format_stack():\n%s\n\n", "".join( traceback.format_stack() ) )
279 
Here is the call graph for this function:

◆ warn()

def warn (   self,
  msg,
  args,
  kwargs 
)
    Fix second indirection created by the super().warn() method, by directly calling _log()

Definition at line 915 of file logger.py.

References Debugger._log().

915  def warn(self, msg, *args, **kwargs):
916  """
917  Fix second indirection created by the super().warn() method, by directly calling _log()
918  """
919 
920  if self.isEnabledFor( WARNING ):
921  self._log( WARNING, msg, args, **kwargs )
922 
Here is the call graph for this function:

The documentation for this class was generated from the following file: