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