-
Notifications
You must be signed in to change notification settings - Fork 8
/
logSetup.py
160 lines (119 loc) · 4.09 KB
/
logSetup.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
import logging
import colorama as clr
import os.path
import sys
import time
import traceback
# Pyling can't figure out what's in the record library for some reason
#pylint: disable-msg=E1101
colours = [clr.Fore.BLUE, clr.Fore.RED, clr.Fore.GREEN, clr.Fore.YELLOW, clr.Fore.MAGENTA, clr.Fore.CYAN, clr.Back.YELLOW + clr.Fore.BLACK, clr.Back.YELLOW + clr.Fore.BLUE, clr.Fore.WHITE]
def getColor(idx):
return colours[idx%len(colours)]
class ColourHandler(logging.Handler):
def __init__(self, level=logging.DEBUG):
logging.Handler.__init__(self, level)
self.formatter = logging.Formatter('\r%(name)s%(padding)s - %(style)s%(levelname)s - %(message)s'+clr.Style.RESET_ALL)
clr.init()
self.logPaths = {}
def emit(self, record):
# print record.levelname
# print record.name
segments = record.name.split(".")
if segments[0] == "Main" and len(segments) > 1:
segments.pop(0)
segments[0] = "Main."+segments[0]
nameList = []
for indice, pathSegment in enumerate(segments):
if not indice in self.logPaths:
self.logPaths[indice] = [pathSegment]
elif not pathSegment in self.logPaths[indice]:
self.logPaths[indice].append(pathSegment)
name = clr.Style.RESET_ALL
name += getColor(self.logPaths[indice].index(pathSegment))
name += pathSegment
name += clr.Style.RESET_ALL
nameList.append(name)
record.name = ".".join(nameList)
if record.levelname == "DEBUG":
record.style = clr.Style.DIM
elif record.levelname == "WARNING":
record.style = clr.Style.BRIGHT
elif record.levelname == "ERROR":
record.style = clr.Style.BRIGHT+clr.Fore.RED
elif record.levelname == "CRITICAL":
record.style = clr.Style.BRIGHT+clr.Back.BLUE+clr.Fore.RED
else:
record.style = clr.Style.NORMAL
record.padding = ""
print((self.format(record)))
class RobustFileHandler(logging.FileHandler):
"""
A handler class which writes formatted logging records to disk files.
"""
def emit(self, record):
"""
Emit a record.
If the stream was not opened because 'delay' was specified in the
constructor, open it before calling the superclass's emit.
"""
failures = 0
while self.stream is None:
try:
self.stream = self._open()
except:
time.sleep(1)
if failures > 3:
traceback.print_exc()
print("Cannot open log file?")
return
failures += 1
failures = 0
while failures < 3:
try:
logging.StreamHandler.emit(self, record)
break
except:
failures += 1
else:
traceback.print_stack()
print("Error writing to file?")
self.close()
def exceptHook(exc_type, exc_value, exc_traceback):
if issubclass(exc_type, KeyboardInterrupt):
sys.__excepthook__(exc_type, exc_value, exc_traceback)
return
mainLogger = logging.getLogger("Main") # Main logger
mainLogger.critical('Uncaught exception!')
mainLogger.critical("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))
LOGGING_INITIALIZED = False
def initLogging(logLevel=logging.INFO):
global LOGGING_INITIALIZED
if LOGGING_INITIALIZED:
print("ERROR - Logging initialized twice!")
print(traceback.format_exc())
return
LOGGING_INITIALIZED = True
print("Setting up loggers....")
if not os.path.exists(os.path.join("./logs")):
os.mkdir(os.path.join("./logs"))
mainLogger = logging.getLogger("Main") # Main logger
reqLogger = logging.getLogger() # requests
apschd_log = logging.getLogger("apscheduler") # Main logger
mainLogger.setLevel(logLevel)
reqLogger .setLevel(logLevel)
apschd_log.setLevel(logLevel)
ch = ColourHandler()
mainLogger.addHandler(ch)
reqLogger .addHandler(ch)
apschd_log.addHandler(ch)
# logName = "Error - %s.txt" % (time.strftime("%Y-%m-%d %H;%M;%S", time.gmtime()))
# errLogHandler = RobustFileHandler(os.path.join("./logs", logName))
# errLogHandler.setLevel(logging.WARNING)
# formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# errLogHandler.setFormatter(formatter)
# mainLogger.addHandler(errLogHandler)
# Install override for excepthook, to catch all errors
sys.excepthook = exceptHook
# Do not propigate up to the root logger
mainLogger.propagate = False
print("done")