_logging.py 2.2 KB

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