source: branches/hpc34/python/logging.py@ 2803

Last change on this file since 2803 was 2448, checked in by Malte Marquarding, 12 years ago

Fix rcParamsverbose handling. This was ignored.

File size: 3.5 KB
Line 
1"""This module presents a logging abstraction layer on top of casa.
2"""
3__all__ = ["asaplog", "asaplog_post_dec", "AsapLogger"]
4
5import inspect
6import sys
7from asap.env import is_casapy
8from asap.parameters import rcParams
9from asap._asap import LogSink, set_global_sink
10try:
11 from functools import wraps as wraps_dec
12except ImportError:
13 from asap.compatibility import wraps as wraps_dec
14
15
16class AsapLogger(object):
17 """Wrapper object to allow for both casapy and asap logging.
18
19 Inside casapy this will connect to `taskinit.casalog`. Otherwise it will
20 create its own casa log sink.
21
22 .. note:: Do not instantiate a new one - use the :obj:`asaplog` instead.
23
24 """
25 def __init__(self):
26 self._enabled = True
27 self._log = ""
28 if is_casapy():
29 from taskinit import casalog
30 self.logger = casalog
31 else:
32 self.logger = LogSink()
33 set_global_sink(self.logger)
34
35 def post(self, level='INFO', origin=""):
36 """Post the messages to the logger. This will clear the buffered
37 logs.
38
39 Parameters:
40
41 level: The log level (severity). One of INFO, WARN, ERROR.
42
43 """
44 if not self._enabled:
45 return
46
47 if not origin:
48 origin = inspect.getframeinfo(inspect.currentframe().f_back)[2]
49 logs = self._log.strip()
50 if len(logs) > 0:
51 if isinstance(self.logger, LogSink):
52 #can't handle unicode in boost signature
53 logs = str(logs)
54 self.logger.post(logs, priority=level, origin=origin)
55 if isinstance(self.logger, LogSink):
56 logs = self.logger.pop().strip()
57 if len(logs) > 0:
58 if rcParams['verbose']:
59 print >>sys.stdout, logs
60 if hasattr(sys.stdout, "flush"):
61 sys.stdout.flush()
62 self._log = ""
63
64 def clear(self):
65 if isinstance(self.logger, LogSink):
66 logs = self.logger.pop()
67
68 def push(self, msg, newline=True):
69 """Push logs into the buffer. post needs to be called to send them.
70
71 Parameters:
72
73 msg: the log message (string)
74
75 newline: should we terminate with a newline (default yes)
76
77 """
78 if self._enabled:
79 sep = ""
80 self._log = sep.join([self._log, msg])
81 if newline:
82 self._log += "\n"
83
84 def enable(self, flag=True):
85 """Enable (or disable) logging."""
86 self._enabled = flag
87
88 def disable(self, flag=False):
89 """Disable (or enable) logging"""
90 self._enabled = flag
91
92 def is_enabled(self):
93 return self._enabled
94
95asaplog = AsapLogger()
96"""Default asap logger"""
97
98def asaplog_post_dec(f):
99 """Decorator which posts log at completion of the wrapped method.
100
101 Example::
102
103 @asaplog_post_dec
104 def test(self):
105 do_stuff()
106 asaplog.push('testing...', False)
107 do_more_stuff()
108 asaplog.push('finished')
109 """
110 @wraps_dec(f)
111 def wrap_it(*args, **kw):
112 level = "INFO"
113 try:
114 try:
115 val = f(*args, **kw)
116 return val
117 except Exception, ex:
118 level = "ERROR"
119 asaplog.push(str(ex))
120 if rcParams['verbose']:
121 pass
122 else:
123 raise
124 finally:
125 asaplog.post(level, f.func_name)
126 return wrap_it
127
Note: See TracBrowser for help on using the repository browser.