Debian Codegraph @

gavo/user/logui.py

raw
1 """
2 An observer doing logging of warnings, infos, errors, etc.
3
4 No synchronization takes place; it's probably not worth sweating this.
5 """
6
7 #c Copyright 2008-2025, the GAVO project <[email protected]>
8 #c
9 #c This program is free software, covered by the GNU GPL. See the
10 #c COPYING file in the source distribution.
11
12
13 import logging
14 import sys
15 import traceback
16
17 from gavo import base
18 from gavo import utils
19 from gavo.base import ObserverBase, listensTo
20 from gavo.protocols.gavolog import getLoggingHandler
21
22
23 def stringify(s):
24 if isinstance(s, bytes):
25 return s.decode("utf-8", "ignore")
26 # logging gives us a headache when there's non-ascii in here;
27 # pending further investigation, hack around it:
28 return s.encode("ascii", "replace").decode("ascii")
29
30
31 def addRequestURI(msg):
32 """adds info on the request URI to msg if we seem to handle a request.
33
34 (which, technically, we determine by trying to steal a request variable
35 from upstack).
36 """
37 try:
38 req = utils.stealVar("request")
39 if req:
40 msg = "While handling %s:\n%s"%(
41 req.uri.decode("ascii"),
42 msg)
43 except:
44 # don't fail if we can't add the request URI for some reason;
45 # people will notice anyway.
46 pass
47 return msg
48
49
50 class LoggingUI(ObserverBase):
51 logLineFormat = "%(asctime)s [%(levelname)s %(process)s] %(message)s"
52
53 def __init__(self, eh, errorName="dcErrors", infoName="dcInfos"):
54 ObserverBase.__init__(self, eh)
55 errH = getLoggingHandler(
56 base.getConfig("logDir") / errorName, "errors")
57 errH.setFormatter(
58 logging.Formatter(self.logLineFormat))
59 self.errorLogger = logging.getLogger("dcErrors")
60 self.errorLogger.addHandler(errH)
61 self.errorLogger.propagate = False
62
63 infoH = getLoggingHandler(
64 base.getConfig("logDir") / infoName,
65 "infos",
66 backupCount=1)
67 infoH.setFormatter(logging.Formatter(self.logLineFormat))
68 self.infoLogger = logging.getLogger("dcInfos")
69 self.infoLogger.propagate = False
70 self.infoLogger.addHandler(infoH)
71 self.infoLogger.setLevel(logging.DEBUG)
72
73 @listensTo("ExceptionMutation")
74 def logOldException(self, res):
75 if base.DEBUG:
76 excInfo, newExc = res
77 self.infoLogger.info("Swallowed the exception below, re-raising %s"%
78 repr(newExc), exc_info=excInfo)
79
80 @listensTo("Info")
81 def logInfo(self, message):
82 self.infoLogger.info(
83 addRequestURI(
84 stringify(message)))
85
86 @listensTo("Warning")
87 def logWarning(self, message):
88 self.infoLogger.warning(
89 addRequestURI(
90 stringify(message)))
91
92 @listensTo("Error")
93 def logError(self, message):
94 self.errorLogger.error(
95 addRequestURI(
96 utils.safe_str(message)), exc_info=False)
97 if sys.exc_info()!=(None, None, None):
98 self.infoLogger.info("Traceback (le) of the exception just logged:\n%s"%
99 traceback.format_exc())