forked from panda3d/panda3d
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNotifier.py
More file actions
300 lines (264 loc) · 9.82 KB
/
Notifier.py
File metadata and controls
300 lines (264 loc) · 9.82 KB
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
289
290
291
292
293
294
295
296
297
298
299
"""
Notifier module: contains methods for handling information output
for the programmer/user
"""
from .LoggerGlobal import defaultLogger
from direct.showbase import PythonUtil
from panda3d.core import ConfigVariableBool, NotifyCategory, StreamWriter, Notify
import time
import sys
class Notifier:
serverDelta = 0
# If this object is set to something, it is used to print output
# messages instead of writing them to the console. This is
# particularly useful for integrating the Python notify system
# with the C++ notify system.
streamWriter = None
if ConfigVariableBool('notify-integrate', True):
streamWriter = StreamWriter(Notify.out(), False)
showTime = ConfigVariableBool('notify-timestamp', False)
def __init__(self, name, logger=None):
"""
Parameters:
name (str): a string name given to this Notifier instance.
logger (Logger, optional): an optional Logger object for
piping output to. If none is specified, the global
:data:`~.LoggerGlobal.defaultLogger` is used.
"""
self.__name = name
if (logger==None):
self.__logger = defaultLogger
else:
self.__logger = logger
# Global default levels are initialized here
self.__info = 1
self.__warning = 1
self.__debug = 0
self.__logging = 0
def setServerDelta(self, delta, timezone):
"""
Call this method on any Notify object to globally change the
timestamp printed for each line of all Notify objects.
This synchronizes the timestamp with the server's known time
of day, and also switches into the server's timezone.
"""
delta = int(round(delta))
Notifier.serverDelta = delta + time.timezone - timezone
# The following call is necessary to make the output from C++
# notify messages show the same timestamp as those generated
# from Python-level notify messages.
NotifyCategory.setServerDelta(self.serverDelta)
self.info("Notify clock adjusted by %s (and timezone adjusted by %s hours) to synchronize with server." % (PythonUtil.formatElapsedSeconds(delta), (time.timezone - timezone) / 3600))
def getTime(self):
"""
Return the time as a string suitable for printing at the
head of any notify message
"""
# for some strange reason, time.time() updates only once/minute if
# the task is out of focus on win32. time.clock doesn't have this problem.
return time.strftime(":%m-%d-%Y %H:%M:%S ", time.localtime(time.time() + self.serverDelta))
def getOnlyTime(self):
"""
Return the time as a string.
The Only in the name is referring to not showing the date.
"""
return time.strftime("%H:%M:%S", time.localtime(time.time() + self.serverDelta))
def __str__(self):
"""
Print handling routine
"""
return "%s: info = %d, warning = %d, debug = %d, logging = %d" % \
(self.__name, self.__info, self.__warning, self.__debug, self.__logging)
# Severity funcs
def setSeverity(self, severity):
from panda3d.core import NSDebug, NSInfo, NSWarning, NSError
if severity >= NSError:
self.setWarning(0)
self.setInfo(0)
self.setDebug(0)
elif severity == NSWarning:
self.setWarning(1)
self.setInfo(0)
self.setDebug(0)
elif severity == NSInfo:
self.setWarning(1)
self.setInfo(1)
self.setDebug(0)
elif severity <= NSDebug:
self.setWarning(1)
self.setInfo(1)
self.setDebug(1)
def getSeverity(self):
from panda3d.core import NSDebug, NSInfo, NSWarning, NSError
if self.getDebug():
return NSDebug
elif self.getInfo():
return NSInfo
elif self.getWarning():
return NSWarning
else:
return NSError
# error funcs
def error(self, errorString, exception=Exception):
"""
Raise an exception with given string and optional type:
Exception: error
"""
message = str(errorString)
if Notifier.showTime.getValue():
string = (self.getTime() + str(exception) + ": " + self.__name + "(error): " + message)
else:
string = (str(exception) + ": " + self.__name + "(error): " + message)
self.__log(string)
raise exception(errorString)
# warning funcs
def warning(self, warningString):
"""
Issue the warning message if warn flag is on
"""
if self.__warning:
message = str(warningString)
if Notifier.showTime.getValue():
string = (self.getTime() + self.__name + '(warning): ' + message)
else:
string = (":" + self.__name + '(warning): ' + message)
self.__log(string)
self.__print(string)
return 1 # to allow assert myNotify.warning("blah")
def setWarning(self, bool):
"""
Enable/Disable the printing of warning messages
"""
self.__warning = bool
def getWarning(self):
"""
Return whether the printing of warning messages is on or off
"""
return(self.__warning)
# debug funcs
def debug(self, debugString):
"""
Issue the debug message if debug flag is on
"""
if self.__debug:
message = str(debugString)
if Notifier.showTime.getValue():
string = (self.getTime() + self.__name + '(debug): ' + message)
else:
string = (':' + self.__name + '(debug): ' + message)
self.__log(string)
self.__print(string)
return 1 # to allow assert myNotify.debug("blah")
def setDebug(self, bool):
"""
Enable/Disable the printing of debug messages
"""
self.__debug = bool
def getDebug(self):
"""
Return whether the printing of debug messages is on or off
"""
return self.__debug
# info funcs
def info(self, infoString):
"""
Print the given informational string, if info flag is on
"""
if self.__info:
message = str(infoString)
if Notifier.showTime.getValue():
string = (self.getTime() + self.__name + ': ' + message)
else:
string = (':' + self.__name + ': ' + message)
self.__log(string)
self.__print(string)
return 1 # to allow assert myNotify.info("blah")
def getInfo(self):
"""
Return whether the printing of info messages is on or off
"""
return self.__info
def setInfo(self, bool):
"""
Enable/Disable informational message printing
"""
self.__info = bool
# log funcs
def __log(self, logEntry):
"""
Determine whether to send informational message to the logger
"""
if self.__logging:
self.__logger.log(logEntry)
def getLogging(self):
"""
Return 1 if logging enabled, 0 otherwise
"""
return (self.__logging)
def setLogging(self, bool):
"""
Set the logging flag to int (1=on, 0=off)
"""
self.__logging = bool
def __print(self, string):
"""
Prints the string to output followed by a newline.
"""
if self.streamWriter:
self.streamWriter.write(string + '\n')
else:
sys.stderr.write(string + '\n')
def debugStateCall(self, obj=None, fsmMemberName='fsm',
secondaryFsm='secondaryFSM'):
"""
If this notify is in debug mode, print the time of the
call followed by the [fsm state] notifier category and
the function call (with parameters).
"""
#f.f_locals['self'].__init__.im_class.__name__
if self.__debug:
state = ''
doId = ''
if obj is not None:
fsm=obj.__dict__.get(fsmMemberName)
if fsm is not None:
stateObj = fsm.getCurrentState()
if stateObj is not None:
#state = "%s=%s"%(fsmMemberName, stateObj.getName())
state = stateObj.getName()
fsm=obj.__dict__.get(secondaryFsm)
if fsm is not None:
stateObj = fsm.getCurrentState()
if stateObj is not None:
#state = "%s=%s"%(fsmMemberName, stateObj.getName())
state = "%s, %s"%(state, stateObj.getName())
if hasattr(obj, 'doId'):
doId = " doId:%s"%(obj.doId,)
#if type(obj) == types.ClassType:
# name = "%s."%(obj.__class__.__name__,)
string = ":%s:%s [%-7s] id(%s)%s %s"%(
self.getOnlyTime(),
self.__name,
state,
id(obj),
doId,
PythonUtil.traceParentCall())
self.__log(string)
self.__print(string)
return 1 # to allow assert self.notify.debugStateCall(self)
def debugCall(self, debugString=''):
"""
If this notify is in debug mode, print the time of the
call followed by the notifier category and
the function call (with parameters).
"""
if self.__debug:
message = str(debugString)
string = ":%s:%s \"%s\" %s"%(
self.getOnlyTime(),
self.__name,
message,
PythonUtil.traceParentCall())
self.__log(string)
self.__print(string)
return 1 # to allow assert self.notify.debugCall("blah")