-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.py
225 lines (197 loc) · 7.47 KB
/
logger.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
"""
Custom logger by me, since I'm not a fan of the standard logging module
"""
# TODO: Add documentation
import os
import json
from enum import Enum
from colorama import just_fix_windows_console
__all__ = ["LoggingLevel", "Logging", "logging", "enable_logging", "disable_logging"]
class LoggingLevel(Enum):
Debug = 1
Info = 2
Important = 3
VeryImportant = 4
SuperImportant = 5
Warning = 6
class Logging:
def __init__(self, usedefaults: bool = True, synclog: bool = True, **kwargs) -> None:
"""
:param usedefaults: Whether to use the default logging settings
:param synclog: Whether to sync the Log list with other instances of this class
:param kwargs: If usedefaults is False, supply your own logging settings here:
colorized=True
printwarnings=True
printdebug=False
printinfo=True
printimportant=True
printveryimportant=True
printsuperimportant=True
printspecial=True
donotprintspecial=False
donotprintsuccessinfo=False
allowoverride=True
printall=True
printnone=False
"""
if usedefaults:
self._fromoptions(**_loadconfig())
else:
self._fromoptions(**kwargs)
if synclog:
self.Log = _Log
else:
self.Log = []
self.enabled = True
def _fromoptions(self,
colorized=True,
printwarnings=True,
printdebug=False,
printinfo=True,
printimportant=True,
printveryimportant=True,
printsuperimportant=True,
printspecial=True,
donotprintspecial=False,
donotprintsuccessinfo=False,
allowoverride=True,
printall=True,
printnone=False
):
self.colorized = colorized
self.printwarnings = printwarnings
self.printdebug = printdebug
self.printinfo = printinfo
self.printimportant = printimportant
self.printveryimportant = printveryimportant
self.printsuperimportant = printsuperimportant
self.printspecial = printspecial
self.donotprintspecial = donotprintspecial
self.donotprintsuccessinfo = donotprintsuccessinfo
self.allowoverride = allowoverride
self.printall = printall
self.printnone = printnone
def enable(self):
self.enabled = True
def disable(self):
self.enabled = False
def log(self, message: str, level: LoggingLevel = LoggingLevel.Info, override: bool = False,
successinfo: bool = False, special: bool = False) -> None:
self.Log.append(message)
if self.printnone:
return
if not (override and self.allowoverride):
if successinfo and self.donotprintsuccessinfo:
return
if special and self.donotprintspecial:
return
if self.printall:
toprint = True
elif level == LoggingLevel.Debug and self.printdebug:
toprint = True
elif level == LoggingLevel.Info and self.printinfo:
toprint = True
elif level == LoggingLevel.Important and self.printimportant:
toprint = True
elif level == LoggingLevel.VeryImportant and self.printveryimportant:
toprint = True
elif level == LoggingLevel.SuperImportant and self.printsuperimportant:
toprint = True
elif special and self.printspecial:
toprint = True
else:
toprint = False
if toprint and _enabled and self.enabled:
self.printmessage(message, level, special, self.colorized)
def printlog(self):
print("\n".join(self.Log))
@staticmethod
def printmessage(message: str, level: LoggingLevel, special: bool, colorized: bool) -> None:
colors = {
"Debug": "\033[0m",
"Info": "\033[94m",
"Important": "\033[95m",
"VeryImportant": "\033[96m",
"SuperImportant": "\033[93m",
"Warning": "\033[91m",
"Special": "\033[92m",
"reset": "\033[0m"
}
if colorized:
if special:
print(f"{colors['Special']}[{level.name}] [Special]: {message}{colors['reset']}")
else:
if level.name in colors:
print(f"{colors[level.name]}[{level.name}]: {message}{colors['reset']}")
else:
print(f"[{level.name}]: {message}")
else:
if special:
print(f"[{level.name}] [Special]: {message}")
else:
print(f"[{level.name}]: {message}")
def warning(self, message: str, warningtype: BaseException = None) -> None:
if warningtype:
self.Log.append(f"[Warning]: {warningtype}: {message}")
if self.printwarnings and _enabled and self.enabled:
self.printmessage(f"{warningtype}: {message}", LoggingLevel.Warning, False, self.colorized)
else:
self.Log.append(f"[Warning]: {message}")
if self.printwarnings and _enabled and self.enabled:
self.printmessage(message, LoggingLevel.Warning, False, self.colorized)
def disable_logging() -> None:
"""
Disables logging to console with print statements
"""
global _enabled
_enabled = False
def enable_logging() -> None:
"""
Enables logging to console with print statements
"""
global _enabled
_enabled = True
def _loadconfig() -> dict:
if os.path.exists(configpath):
with open(configpath, "r") as f:
return json.load(f)
else:
"""
loggingconfig.json does not exist, fall back to hardcoded defaults
"""
return _defaults
def _writeconfig(config: dict) -> None:
with open(configpath, "w") as f:
json.dump(config, f, indent=4)
def _config(**kwargs) -> dict:
"""
This is a neat trick that lets me generate a dictionary with my config just by calling
this function with the options as arguments!
"""
return kwargs
_defaults = _config(colorized=True,
printwarnings=True,
printdebug=False,
printinfo=True,
printimportant=True,
printveryimportant=True,
printsuperimportant=True,
printspecial=True,
donotprintspecial=False,
donotprintsuccessinfo=False,
allowoverride=True,
printall=True,
printnone=False
)
configpath = os.path.join(os.path.dirname(__file__), "loggingconfig.json")
just_fix_windows_console()
_enabled = True
_Log = []
logging = Logging(usedefaults=True)
if __name__ == "__main__":
if not os.path.exists(configpath):
try:
_writeconfig(_defaults)
print(f"Created loggingconfig.json at {configpath}")
except Exception as e:
print(f"Failed to create loggingconfig.json at {configpath}: {e}")