This repository has been archived by the owner on Dec 8, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
zen_custom.py
289 lines (241 loc) · 10.4 KB
/
zen_custom.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
"""
A collection of classes and decorators
"""
__version__ = '2.4.0'
__author__ = 'desultory'
import logging
from sys import modules
from threading import Thread, Event
from queue import Queue
def update_init(decorator):
"""
Updates the init function of a class
puts the decorated function at the end of the init
"""
def decorator_wrapper(cls):
original_init = cls.__init__
def new_init(self, *args, **kwargs):
original_init(self, *args, **kwargs)
decorator(self)
cls.__init__ = new_init
return cls
return decorator_wrapper
def handle_plural(function):
"""
Wraps functions to take a list/dict and iterate over it
the last argument should be iterable
"""
def wrapper(self, *args):
if len(args) == 1:
focus_arg = args[0]
other_args = tuple()
else:
focus_arg = args[-1]
other_args = args[:-1]
if isinstance(focus_arg, list) and not isinstance(focus_arg, str):
for item in focus_arg:
function(self, *(other_args + (item,)))
elif isinstance(focus_arg, dict):
for key, value in focus_arg.items():
function(self, *(other_args + (key, value,)))
else:
self.logger.debug("Arguments were not expanded: %s" % args)
function(self, *args)
return wrapper
def threaded(function):
"""
Simply starts a function in a thread
Adds it to an internal _threads list for handling
"""
def wrapper(self, *args, **kwargs):
if not hasattr(self, '_threads'):
self._threads = list()
thread_exception = Queue()
def exception_wrapper(*args, **kwargs):
try:
function(*args, **kwargs)
except Exception as e:
self.logger.warning("Exception in thread: %s" % function.__name__)
thread_exception.put(e)
self.logger.debug(e)
thread = Thread(target=exception_wrapper, args=(self, *args), kwargs=kwargs, name=function.__name__)
thread.start()
self._threads.append((thread, thread_exception))
return wrapper
def add_thread(name, target, description=None):
"""
Adds a thread of a class which targets the target
Creates a dict that contains the name of the thread as a key, with the thread as a value
Cteates basic helper functions to manage the thread
"""
def decorator(cls):
def create_thread(self):
if not hasattr(self, 'threads'):
self.threads = dict()
if "." in target:
target_parts = target.split(".")
target_attr = self
for part in target_parts:
target_attr = getattr(target_attr, part)
else:
target_attr = getattr(self, target)
self.threads[name] = Thread(target=target_attr, name=description)
self.logger.info("Created thread: %s" % name)
def start_thread(self):
thread = self.threads[name]
setattr(self, f"_stop_processing_{name}", Event())
if thread._is_stopped:
self.logger.info("Re-creating thread")
getattr(self, f"create_{name}_thread")()
thread = self.threads[name]
if thread._started.is_set() and not thread._is_stopped:
self.logger.warning("%s thread is already started" % name)
else:
self.logger.info("Starting thread: %s" % name)
thread.start()
def stop_thread(self):
thread = self.threads[name]
getattr(self, f"_stop_processing_{name}").set()
if not thread._started.is_set() or thread._is_stopped:
self.logger.warning("Thread is not active: %s" % name)
else:
if hasattr(self, f"stop_{name}_thread_actions"):
self.logger.debug("Calling: %s" % f"stop_{name}_thread_actions")
getattr(self, f"stop_{name}_thread_actions")()
if hasattr(self, f"_{name}_timer"):
self.logger.info("Stopping the timer for thread: %s" % name)
getattr(self, f"_{name}_timer").cancel()
self.logger.info("Waiting on thread to end: %s" % name)
thread.join()
setattr(cls, f"create_{name}_thread", create_thread)
setattr(cls, f"start_{name}_thread", start_thread)
setattr(cls, f"stop_{name}_thread", stop_thread)
return update_init(create_thread)(cls)
return decorator
def thread_wrapped(thread_name):
"""
Wrap a class function to be used with add_thread
"""
def decorator(function):
def wrapper(self, *args, **kwargs):
self.logger.info("Starting the processing loop for thread: %s" % thread_name)
while not getattr(self, f"_stop_processing_{thread_name}").is_set():
function(self, *args, **kwargs)
self.logger.info("The processing loop has ended for thread: %s" % thread_name)
return wrapper
return decorator
def class_logger(cls):
"""
Decorator for classes to add a logging object and log basic tasks
"""
class ClassWrapper(cls):
def __init__(self, *args, **kwargs):
parent_logger = kwargs.pop('logger') if isinstance(kwargs.get('logger'), logging.Logger) else logging.getLogger()
self.logger = parent_logger.getChild(cls.__name__)
self.logger.setLevel(self.logger.parent.level)
def has_handler(logger):
parent = logger
while parent:
if parent.handlers:
return True
parent = parent.parent
return False
if not has_handler(self.logger):
color_stream_handler = logging.StreamHandler()
color_stream_handler.setFormatter(ColorLognameFormatter())
self.logger.addHandler(color_stream_handler)
self.logger.info("Adding default handler: %s" % self.logger)
if kwargs.get('_log_init', True) is True:
self.logger.info("Intializing class: %s" % cls.__name__)
if args:
self.logger.debug("Args: %s" % repr(args))
if kwargs:
self.logger.debug("Kwargs: %s" % repr(kwargs))
if module_version := getattr(modules[cls.__module__], '__version__', None):
self.logger.info("Module version: %s" % module_version)
if class_version := getattr(cls, '__version__', None):
self.logger.info("Class version: %s" % class_version)
else:
self.logger.log(5, "Init debug logging disabled for: %s" % cls.__name__)
super().__init__(*args, **kwargs)
def __setattr__(self, name, value):
super().__setattr__(name, value)
if not isinstance(self.logger, logging.Logger):
raise ValueError("The logger is not defined")
if isinstance(value, list) or isinstance(value, dict) or isinstance(value, str) and "\n" in value:
self.logger.log(5, "Set '%s' to:\n%s" % (name, value))
else:
self.logger.log(5, "Set '%s' to: %s" % (name, value))
ClassWrapper.__name__ = cls.__name__
ClassWrapper.__module__ = cls.__module__
ClassWrapper.__qualname__ = cls.__qualname__
return ClassWrapper
class ColorLognameFormatter(logging.Formatter):
"""
ColorLognameFormatter Class
Add the handler to the stdout handler using:
stdout_handler = logging.StreamHandler()
stdout_handler.setFormatter(ColorLognameFormatter())
"""
_level_str_len = 8
# Define the color codes
_reset_str = '\x1b[0m'
_grey_str = '\x1b[37m'
_blue_str = '\x1b[34m'
_yllw_str = '\x1b[33m'
_sred_str = '\x1b[31m'
_bred_str = '\x1b[31;1m'
_magenta_str = '\x1b[35m'
# Make the basic strings
_debug_color_str = f"{_grey_str}DEBUG{_reset_str}".ljust(
_level_str_len + len(_reset_str) + len(_grey_str), ' ')
_info_color_str = f"{_blue_str}INFO{_reset_str}".ljust(
_level_str_len + len(_reset_str) + len(_blue_str), ' ')
_warn_color_str = f"{_yllw_str}WARNING{_reset_str}".ljust(
_level_str_len + len(_reset_str) + len(_yllw_str), ' ')
_error_color_str = f"{_sred_str}ERROR{_reset_str}".ljust(
_level_str_len + len(_reset_str) + len(_sred_str), ' ')
_crit_color_str = f"{_bred_str}CRITICAL{_reset_str}".ljust(
_level_str_len + len(_reset_str) + len(_bred_str), ' ')
# Format into a dict
_color_levelname = {'DEBUG': _debug_color_str,
'INFO': _info_color_str,
'WARNING': _warn_color_str,
'ERROR': _error_color_str,
'CRITICAL': _crit_color_str}
def __init__(self, fmt='%(levelname)s | %(message)s', *args, **kwargs):
super().__init__(fmt, *args, **kwargs)
def format(self, record):
# When calling format, replace the levelname with a colored version
# Note: the string size is greatly increased because of the color codes
old_levelname = record.levelname
if record.levelname in self._color_levelname:
record.levelname = self._color_levelname[record.levelname]
else:
record.levelname = f"{self._magenta_str}{record.levelname}{self._reset_str}".ljust(
self._level_str_len + len(self._magenta_str) + len(self._reset_str), ' ')
format_str = super().format(record)
try:
record.levelname = old_levelname
except NameError:
pass
return format_str
@class_logger
class NoDupFlatList(list):
"""
List that automatically filters duplicate elements when appended and concatenated
"""
__version__ = "0.2.0"
def __init__(self, no_warn=False, log_bump=0, *args, **kwargs):
self.no_warn = no_warn
self.logger.setLevel(self.logger.parent.level + log_bump)
@handle_plural
def append(self, item):
if item not in self:
self.logger.debug("Adding list item: %s" % item)
super().append(item)
elif not self.no_warn:
self.logger.warning("List item already exists: %s" % item)
def __iadd__(self, item):
self.append(item)
return self