loghandler.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import logging
  2. class VTKHandler(logging.Handler):
  3. def __init__(self, *args, **kwargs):
  4. super(VTKHandler, self).__init__(*args, **kwargs)
  5. def emit(self, record):
  6. try:
  7. from vtkmodules.vtkCommonCore import vtkLogger
  8. msg = self.format(record)
  9. lvl = self.get_vtk_level(record.levelno)
  10. vtkLogger.Log(\
  11. lvl,
  12. record.filename,
  13. record.lineno,
  14. msg)
  15. from vtkmodules.vtkCommonCore import vtkOutputWindow as win
  16. outputWindow = win.GetInstance()
  17. if outputWindow:
  18. # do not duplicate on standard output
  19. prevMode = outputWindow.GetDisplayMode()
  20. outputWindow.SetDisplayModeToNever()
  21. if lvl == vtkLogger.VERBOSITY_ERROR:
  22. lvlText = 'ERR: '
  23. fullMsg = f"{record.filename}:{record.lineno} {lvlText}{msg}\n"
  24. outputWindow.DisplayErrorText(fullMsg)
  25. elif lvl == vtkLogger.VERBOSITY_WARNING:
  26. lvlText = 'WARN: '
  27. fullMsg = f"{record.filename}:{record.lineno} {lvlText}{msg}\n"
  28. outputWindow.DisplayWarningText(fullMsg)
  29. else:
  30. fullMsg = f"{record.filename}:{record.lineno} {msg}\n"
  31. outputWindow.DisplayText(fullMsg)
  32. outputWindow.SetDisplayMode(prevMode)
  33. except Exception:
  34. self.handleError(record)
  35. def get_vtk_level(self, level):
  36. from vtkmodules.vtkCommonCore import vtkLogger
  37. if level >= logging.ERROR:
  38. return vtkLogger.VERBOSITY_ERROR
  39. elif level >= logging.WARNING:
  40. return vtkLogger.VERBOSITY_WARNING
  41. elif level >= logging.INFO:
  42. return vtkLogger.VERBOSITY_INFO
  43. elif level >= logging.DEBUG:
  44. return vtkLogger.VERBOSITY_TRACE
  45. else:
  46. return vtkLogger.VERBOSITY_MAX
  47. def get_level(vtklevel=None):
  48. """returns current log level used by vtkLogger"""
  49. from vtkmodules.vtkCommonCore import vtkLogger
  50. vtk_level = vtkLogger.GetCurrentVerbosityCutoff() if vtklevel is None else vtklevel
  51. if vtk_level == vtkLogger.VERBOSITY_ERROR:
  52. return logging.ERROR
  53. elif vtk_level == vtkLogger.VERBOSITY_WARNING:
  54. return logging.WARNING
  55. elif vtk_level == vtkLogger.VERBOSITY_INFO:
  56. return logging.INFO
  57. else:
  58. return logging.DEBUG