_logging.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. """
  2. """
  3. """
  4. _logging.py
  5. websocket - WebSocket client library for Python
  6. Copyright 2021 engn33r
  7. Licensed under the Apache License, Version 2.0 (the "License");
  8. you may not use this file except in compliance with the License.
  9. You may obtain a copy of the License at
  10. http://www.apache.org/licenses/LICENSE-2.0
  11. Unless required by applicable law or agreed to in writing, software
  12. distributed under the License is distributed on an "AS IS" BASIS,
  13. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. See the License for the specific language governing permissions and
  15. limitations under the License.
  16. """
  17. import logging
  18. _logger = logging.getLogger('websocket')
  19. try:
  20. from logging import NullHandler
  21. except ImportError:
  22. class NullHandler(logging.Handler):
  23. def emit(self, record):
  24. pass
  25. _logger.addHandler(NullHandler())
  26. _traceEnabled = False
  27. __all__ = ["enableTrace", "dump", "error", "warning", "debug", "trace",
  28. "isEnabledForError", "isEnabledForDebug", "isEnabledForTrace"]
  29. def enableTrace(traceable, handler=logging.StreamHandler()):
  30. """
  31. Turn on/off the traceability.
  32. Parameters
  33. ----------
  34. traceable: bool
  35. If set to True, traceability is enabled.
  36. """
  37. global _traceEnabled
  38. _traceEnabled = traceable
  39. if traceable:
  40. _logger.addHandler(handler)
  41. _logger.setLevel(logging.ERROR)
  42. def dump(title, message):
  43. if _traceEnabled:
  44. _logger.debug("--- " + title + " ---")
  45. _logger.debug(message)
  46. _logger.debug("-----------------------")
  47. def error(msg):
  48. _logger.error(msg)
  49. def warning(msg):
  50. _logger.warning(msg)
  51. def debug(msg):
  52. _logger.debug(msg)
  53. def trace(msg):
  54. if _traceEnabled:
  55. _logger.debug(msg)
  56. def isEnabledForError():
  57. return _logger.isEnabledFor(logging.ERROR)
  58. def isEnabledForDebug():
  59. return _logger.isEnabledFor(logging.DEBUG)
  60. def isEnabledForTrace():
  61. return _traceEnabled