Changeset 437


Ignore:
Timestamp:
08/24/2011 05:28:50 PM (11 years ago)
Author:
marcus
Message:
  • refactoring logging for message system usage.
  • message system and logging are initiated automatically on all SeismicHandler?.* imports once
Location:
SHX/trunk
Files:
12 edited

Legend:

Unmodified
Added
Removed
  • SHX/trunk

    • Property svn:ignore set to
      .pydevproject
      .settings
      .project
  • SHX/trunk/SeismicHandler/__init__.py

    r387 r437  
    2020# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA 
    2121 
    22 # enable obspy patches 
    23 from SeismicHandler.patches.ObsPy import * 
     22import sys 
     23 
     24if "SHXlog" not in sys.modules: 
     25    # enable obspy patches 
     26    import SeismicHandler.patches.ObsPy as SHXpatches 
     27 
     28    # activate logging and history 
     29    import SeismicHandler.modules.log as SHXlog 
     30    import SeismicHandler.modules.history as SHXhistory 
  • SHX/trunk/SeismicHandler/basics/command.py

    r276 r437  
    1616#    along with SHX.  If not, see <http://www.gnu.org/licenses/>. 
    1717 
    18 from SeismicHandler.modules.log import getLogger 
    19 from SeismicHandler.modules.messages import MessageService, Message 
    20 from SeismicHandler.core import history 
     18from SeismicHandler.modules.messages import MessageSystem as msgs 
    2119from SeismicHandler.basics.error import ShxError 
    2220 
     
    2725    Ancestor class for all commands using new parser 
    2826    """ 
    29  
    30     # all instances share the logger 
    31     logger = None 
    3227 
    3328    # if set, number of parameters will be checked 
     
    4136 
    4237    def __init__(self, *args, **kwargs): 
    43         # append command to history 
    44         history(self.__class__.__name__, args, kwargs) 
    45  
    46         # init logger 
    47         if not self.logger: 
    48             self.logger = getLogger("command.run") 
    49  
    5038        # transfer known qualifiers 
    5139        self.qualifiers = {} 
     
    9684            self.symbols = None 
    9785 
    98         self.logger.debug("%s: %s, %s" % (self.__class__.__name__, \ 
    99                                               self.parameters, self.qualifiers)) 
    100  
    10186        try: 
    10287            if not len(self.parameters) in self.numberOfParameters: 
     
    10691            pass 
    10792 
     93        msgs.sendMessage("log.debug.command", msg=self.__class__.__name__) 
     94 
    10895        if hasattr(self, "run"): 
    10996            self.run() 
     
    11198            raise NotImplementedError 
    11299 
    113         MessageService.trigger(Message(Message.COMMANDRUN)) 
     100        msgs.sendMessage("command.run", cmd=self.__class__.__name__, \ 
     101                                  args=self.parameters, kwargs=self.qualifiers) 
    114102 
    115103    def help(self): 
  • SHX/trunk/SeismicHandler/basics/error.py

    r286 r437  
    2222"""module for SHX exceptions""" 
    2323 
    24 from SeismicHandler.modules.log import getLogger 
     24from SeismicHandler.modules.messages import MessageSystem as msgs 
    2525from SeismicHandler.basics import Singleton 
    2626 
     27__all__ = ['ShxError', 'ShxWarning'] 
     28 
    2729class Error(Exception): 
     30    """ 
     31    Base exception class. 
     32    """ 
     33 
    2834    __metaclass__ = Singleton 
    2935     
    30     logger = None 
    31  
    3236    def __init__(self): 
    33         if not self.logger: 
    34             self.logger = getLogger("basics.error") 
    35  
    36         # get log level 
    3737        try: 
    38             log = getattr(self.logger, self.level) 
    39         except: 
    40             log = self.logger.debug 
     38            level = self.level 
     39        except AttributeError: 
     40            level = "debug" 
    4141 
    4242        # log message 
    43         try: 
    44             log(": ".join((self.__class__.__name__, self.value))) 
    45         except AttributeError: 
    46             log(self.__class__.__name__) 
    47  
    48 class ShxError(Error): 
    49     def __init__(self, value, level="debug"): 
    50         """ 
    51         """ 
    52         self.value = value 
    53         self.level = level 
    54         Error.__init__(self) 
     43        msgs.sendMessage("log.%s" % level, msg=str(self)) 
    5544 
    5645    def __str__(self): 
    5746        return self.value 
    5847 
    59 # abandoned error classes 
    60 # to be removed XXX 
    6148 
    62 class MultipleLibError(Error): 
    63     def __init__(self): 
     49class ShxError(Error): 
     50    """ 
     51    Standard error used in SHX. By inheritance all errors will be sent to 
     52    logfile via message system. 
     53    """ 
     54 
     55    def __init__(self, value): 
     56        self.value = value 
     57        self.level = "error" 
     58        Error.__init__(self) 
     59     
     60 
     61class ShxWarning(Error): 
     62    """ 
     63    Standard warning. 
     64    """ 
     65 
     66    def __init__(self, value): 
     67        self.value = value 
     68        self.level = "warning" 
    6469        Error.__init__(self) 
    6570 
    66     def __str__(self): 
    67         return "multiple usage of shared library currently not supported" 
    6871 
    69 class CommandStreamError(Error): 
    70     def __init__(self): 
    71         Error.__init__(self) 
    72  
    73     def __str__(self): 
    74         return "commands must be passed as readable stream (file-like object)" 
    75  
    76 class GotoTargetNotFoundError(Error): 
    77     def __init__(self, target): 
    78         Error.__init__(self) 
    79         self.target = target 
    80  
    81     def __str__(self): 
    82         return """Scripting: GOTO target "%s" not found!""" % self.target 
    83  
    84 class CommandRemovedError(Error): 
    85     def __init__(self, cmd): 
    86         Error.__init__(self) 
    87         self.cmd = cmd 
    88  
    89     def __str__(self): 
    90         return """Command "%s" was removed!""" % self.cmd 
    91  
    92 class CommandNotSuccessfulError(Error): 
    93     def __init__(self, cmd, errorcode): 
    94         Error.__init__(self) 
    95         self.cmd = cmd 
    96         self.code = errorcode 
    97  
    98     def __str__(self): 
    99         return """Command "%s" failed with error code %u!""" % (self.cmd, self.code) 
    100  
    101 class InfoEntryNotFoundError(Error): 
    102     def __init__(self, name): 
    103         Error.__init__(self) 
    104         self.name = name 
    105  
    106     def __str__(self): 
    107         return """info entry "%s" not found!""" % self.name 
    108  
    109 class InfoEntryReadOnlyError(Error): 
    110     def __init__(self, name): 
    111         Error.__init__(self) 
    112         self.name = name 
    113  
    114     def __str__(self): 
    115         return """info entry "%s" not writable!""" % self.name 
    116  
    117 class VarsSystemReadOnlyError(Error): 
    118     def __init__(self): 
    119         Error.__init__(self) 
    120  
    121     def __str__(self): 
    122         return """internal variables are unchangeable!""" 
    123  
    124 class VarsSymbolNotFoundError(Error): 
    125     def __init__(self, name): 
    126         Error.__init__(self) 
    127         self.name = name 
    128  
    129     def __str__(self): 
    130         return """symbol '%s' not found!""" % self.name 
    131  
    132 class VarsSymbolGlobalLocalError(Error): 
    133     def __init__(self, name): 
    134         Error.__init__(self) 
    135         self.name = name 
    136  
    137     def __str__(self): 
    138         return """symbol '%s' already defined in local scope!""" % self.name 
     72if __name__ == "__main__": 
     73    try: 
     74        raise ShxWarning("test") 
     75    except: 
     76        pass 
  • SHX/trunk/SeismicHandler/core/__init__.py

    r435 r437  
    2222from SeismicHandler.basics import codes 
    2323from SeismicHandler.modules.traces import Traces as sh_traces 
    24 from SeismicHandler.modules.history import History as history 
    2524 
    2625from obspy.core import read as obspy_read 
  • SHX/trunk/SeismicHandler/modules/history.py

    r258 r437  
    11# -*- coding: utf-8 -*- 
    22# 
    3 # Copyright (C) 2008-2010 Marcus Walther (walther@szgrf.bgr.de) 
     3# Copyright (C) 2008-2011 Marcus Walther (walther@szgrf.bgr.de) 
    44# 
    55# This file is part of Seismic Handler eXtended (SHX) 
     
    2020# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA 
    2121 
    22 """history function for SHX""" 
     22""" 
     23History function for SHX. All commands are populated via message system and can 
     24be fetched from it. 
     25""" 
    2326 
     27from time import time 
    2428from SeismicHandler.basics import Singleton 
    25 from time import time 
     29from SeismicHandler.modules.messages import MessageSystem as msgs 
    2630 
    2731class History(object): 
     
    2933    history = [] 
    3034     
    31     def __init__(self, cmd, args, kwargs): 
    32         """save history entry""" 
    33          
     35    def __init__(self): 
     36        msgs.subscribe(self.addCommand, 'command.run') 
     37 
     38    def addCommand(self, cmd, args, kwargs): 
    3439        self.history.append((time(), cmd, args, kwargs)) 
     40 
     41History() 
  • SHX/trunk/SeismicHandler/modules/log.py

    r435 r437  
    2424from SeismicHandler.basics import Singleton 
    2525from SeismicHandler.config import Settings 
    26 from SeismicHandler.utils.pubsub import pub as msgs 
     26from SeismicHandler.modules.messages import MessageSystem as msgs 
    2727 
    2828import logging 
     
    120120        return logging.getLogger(name) 
    121121 
    122     def receiveMessages(self, msg, topic=msgs.AUTO_TOPIC): 
     122    def receiveMessages(self, message, topic=msgs.AUTO_TOPIC): 
    123123        """ 
    124124        Subscribed to MessageSystem. 
     
    138138        try: 
    139139            logger = getattr(l, mode) 
    140             logger(msg) 
     140            logger(message) 
    141141        except: 
    142142            raise ValueError("Unknown logging mode '%s'!" % mode) 
     
    146146 
    147147if __name__ == "__main__": 
    148     msgs.sendMessage('log.info', msg='Log Info Message') 
    149     msgs.sendMessage('log.error', msg='Log Error Message') 
    150     msgs.sendMessage('log.debug', msg='Log Debug Message') 
     148    msgs.sendMessage('log.info', message='Log Info Message') 
     149    msgs.sendMessage('log.error', message='Log Error Message') 
     150    msgs.sendMessage('log.debug', message='Log Debug Message') 
    151151    msgs.sendMessage('log.debug.traces.test', 
    152                                       msg='Log Debug Message in "traces.test"') 
     152                                  message='Log Debug Message in "traces.test"') 
  • SHX/trunk/SeismicHandler/modules/messages.py

    r276 r437  
    2020# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA 
    2121 
    22 """Events class 
    23  
    24     - simple event manager 
     22""" 
     23Simple message system using pubsub as basis. pubsub details should be hidden 
     24from client software, since this system is maybe changed in later versions. 
    2525""" 
    2626 
    27 from SeismicHandler.modules.log import getLogger 
    28 from SeismicHandler.basics.error import ShxError 
    29  
    30 class Message(object): 
    31     """ 
    32     Event class. 
    33  
    34     Implemented as multiton, so that equal id's are represented by identical 
    35     instances. 
    36     """ 
    37  
    38     _instances = {} 
    39  
    40     # standard events 
    41     TRACEUPDATE = "traceupdate" 
    42     REDRAW = "redraw" 
    43     COMMANDRUN = "cmdrun" 
    44     METAUPDATE = "metaupdate" 
    45  
    46     def __new__(cls, id): 
    47         if not id in cls._instances.keys(): 
    48             cls._instances[id] = object.__new__(cls, id) 
    49  
    50         return cls._instances[id] 
    51  
    52     def __init__(self, id): 
    53         self.name = id 
    54         self.done = False 
    55  
    56 class MessageController(object): 
    57     """ 
    58     Events manager. 
    59  
    60     Subscribing to events: 
    61     >>> def x(e, x): print x*2 
    62     >>> e = MessageController() 
    63     >>> foo = Message("foo") 
    64     >>> bar = Message("bar") 
    65     >>> e.subscribe(foo, x) 
    66     >>> e.subscribe(bar, x) 
    67     >>> sorted([i.name for i in e.events]) 
    68     ['bar', 'foo'] 
    69     >>> e.events[bar] #doctest: +ELLIPSIS 
    70     [<function x at 0x...] 
    71     >>> e.events[foo] #doctest: +ELLIPSIS 
    72     [<function x at 0x...] 
    73  
    74     Now trigger an event: 
    75     >>> e.trigger(foo, 2) 
    76     4 
    77     >>> e.trigger(bar, 7) 
    78     14 
    79  
    80     Events can be blocked to prevent propagation: 
    81     >>> e.block(foo) 
    82     >>> e.trigger(foo, 2) 
    83     >>> e.trigger(foo, 4) 
    84  
    85     If an event is unblocked, pending events can be processed then or discarded. 
    86     Running only the last one is default, None skips processing in total. Here 
    87     we run all pending events with their associated data: 
    88     >>> e.unblock(foo, process="all") 
    89     4 
    90     8 
    91  
    92     Now only the last event queued: 
    93     >>> e.block(foo) 
    94     >>> e.trigger(foo, 3) 
    95     >>> e.trigger(foo, 5) 
    96     >>> e.unblock(foo) 
    97     10 
    98  
    99     A function can be unsubscribed from an event: 
    100     >>> e.unsubscribe(x, foo) 
    101     >>> e.trigger(foo, 111) 
    102     >>> e.trigger(bar, 6) 
    103     12 
    104  
    105     To unsubscribe a function in total, you don't have to know which 
    106     subscriptions are active: 
    107     >>> e.unsubscribe(x) 
    108     >>> e.trigger(foo, 99) 
    109     >>> e.trigger(bar, 6) 
    110     """ 
    111  
    112     events = {} 
    113     blocked = set() 
    114     queue = [] 
    115  
    116     def __init__(self): 
    117         self.logger = getLogger("modules.events") 
    118  
    119     def subscribe(self, events, notify): 
    120         """subscribe to events list 
    121  
    122             - notify must contain a call back function 
    123         """ 
    124  
    125         if not callable(notify): 
    126             raise ShxError("Notifier must be callable!") 
    127  
    128         # change type to list if not iterable 
    129         if not hasattr(events, "__iter__"): 
    130             events = [events, ] 
    131  
    132         for e in events: 
    133             try: 
    134                 self.events[e].append(notify) 
    135             except KeyError: 
    136                 self.events[e] = [notify] 
    137  
    138             self.logger.debug("'%s' subscribed to event '%s'." % (notify, e.name)) 
    139  
    140     def trigger(self, event, *data): 
    141         """trigger event """ 
    142  
    143         if event in self.blocked: 
    144             # save blocked event for later use 
    145             self.queue.append([event, data]) 
    146             self.logger.debug("Event '%s' triggered (but blocked)." % event.name) 
    147             return 
    148  
    149         self.logger.debug("Event '%s' triggered." % event.name) 
    150  
    151         if not self.events.has_key(event): 
    152             self.logger.debug("Event '%s' not found." % event.name) 
    153             return False 
    154  
    155         for i in self.events[event]: 
    156             i(event, *data) 
    157  
    158             # notified function has the possibility to stop further processing 
    159             if event.done: 
    160                 self.logger.debug("Event '%s' propagation stopped by %s." % (event.name, i)) 
    161                 break 
    162  
    163     def unsubscribe(self, notify, events=None): 
    164         """unsubscribe notifier from events """ 
    165  
    166         if not events: 
    167             events = self.events 
    168  
    169         if not hasattr(events, "__iter__"): 
    170             events = [events, ] 
    171  
    172         for e in events: 
    173             if notify in self.events[e]: 
    174                 try: 
    175                     self.logger.debug("'%s' unsubscribed from event '%s'." % (notify, e.name)) 
    176                     self.events[e].remove(notify) 
    177                 except (ValueError): 
    178                     pass 
    179  
    180     def block(self, event): 
    181         """set event on block stage, this means, that the event won't be propagated 
    182         """ 
    183  
    184         self.blocked.update([event]) 
    185  
    186     def unblock(self, event, process="last"): 
    187         """unblock event propagation 
    188  
    189             @param process: 
    190                 control what to do with pending events: 
    191                 None   - discard 
    192                 "last" - only trigger last one 
    193                 "all"  - trigger all 
    194         """ 
    195  
    196         # unblock event 
    197         try: 
    198             self.blocked.remove(event) 
    199         except KeyError: 
    200             return 
    201  
    202         # check if event occurred and maybe trigger it 
    203         # work on a copy of queue 
    204         if process == "last": 
    205             # reverse order 
    206             cqueue = self.queue[::-1] 
    207         else: 
    208             # normal copy 
    209             cqueue = self.queue[:] 
    210  
    211         for pending in cqueue: 
    212             if event != pending[0]: 
    213                 continue 
    214  
    215             self.queue.remove(pending) 
    216  
    217             # skip if requested 
    218             if not process: 
    219                 continue 
    220  
    221             # alter state if only last one should be processed 
    222             if process == "last": 
    223                 process = None 
    224  
    225             self.trigger(pending[0], *pending[1]) 
    226  
    227 MessageService = MessageController() 
    228  
    229 if __name__ == "__main__": 
    230     import doctest 
    231     doctest.testmod() 
     27from SeismicHandler.utils.pubsub import pub as MessageSystem 
  • SHX/trunk/SeismicHandler/modules/miniseed.py

    r287 r437  
    2222from SeismicHandler.basics.error import ShxError 
    2323import os 
    24 from SeismicHandler.core import getLogger 
    2524 
    2625class miniseed(object): 
     
    6564 
    6665    def __init__(self, *args, **kwargs): 
    67         self.logger = log = getLogger("modules.miniseed.sfdfile") 
    68  
    6966        # network, location, stations, stream, component, starttime, endtime/duration 
    7067 
  • SHX/trunk/SeismicHandler/modules/stations.py

    r312 r437  
    2727from SeismicHandler.config import Settings 
    2828from SeismicHandler.basics import Singleton 
    29 from SeismicHandler.modules.log import getLogger 
    3029 
    3130Base = declarative_base() 
     31 
    3232 
    3333class ChannelMeta(Base): 
     
    158158        return not self.__compare(other) 
    159159 
     160 
    160161class FiR(Base): 
    161162    """ 
     
    185186        return "<FIR:%s>" % self.channel 
    186187 
     188 
    187189class Stations(object): 
    188190    """ 
     
    196198 
    197199    def __init__(self): 
    198         self.logger = getLogger("stations") 
    199          
    200200        self.read() 
    201201 
     
    310310            session.rollback() 
    311311 
     312 
    312313if __name__ == "__main__": 
    313314    stations = Stations() 
  • SHX/trunk/SeismicHandler/patches/ObsPy.py

    r434 r437  
    3232from obspy.core.util import AttribDict 
    3333from SeismicHandler.utils.pubsub import pub as msgs 
    34 #from obspy.core import UTCDateTime 
    35  
    36 __all__ = [ 
    37     "patched", 
    38 ] 
     34 
     35__all__ = [] 
    3936 
    4037def _streamAutoMerge(self, *args, **kwargs): 
     
    123120        self.shx.PlotData = pt.data.copy() 
    124121    else: 
    125         msgs.sendMessage('log.devel.patches', message=["using cachedX data for", 
    126                                                               CacheTraceID[:3]]) 
     122        msgs.sendMessage('log.debug.patches.devel', 
     123                           message=["using cachedX data for",CacheTraceID[:3]]) 
    127124 
    128125    # use minmax approach if more than 4 data points per pixel 
     
    150147 
    151148        msgs.sendMessage( 
    152             'log.devel.patches', 
     149            'log.debug.patches.devel', 
    153150            message=[ 
    154151                 "pixel_width", pixel_width, "minmax", "npts", npts, "dpp", 
     
    163160        self.shx.PlotData = joined 
    164161 
    165     msgs.sendMessage('log.devel.patches', 
     162    msgs.sendMessage('log.debug.patches.devel', 
    166163                         message=[width, height, norm, type(self.shx.PlotData)]) 
    167164 
    168165    if cachedY: 
    169         msgs.sendMessage('log.devel.patches', 
     166        msgs.sendMessage('log.debug.patches.devel', 
    170167                           message=["using cachedY data for", CacheTraceID[3:]]) 
    171168        return 
     
    229226Trace.__shx_init__, Trace.__init__ = Trace.__init__, traceAddShxInit 
    230227Trace._shxPrepareImageData = tracePrepareDataForImage 
    231  
    232 # just an indicator 
    233 patched = True 
  • SHX/trunk/sandbox/traceplotter.py

    r436 r437  
    1111from obspy.core.util import AttribDict 
    1212from SeismicHandler.core import read 
    13 from SeismicHandler.utils.pubsub import pub as msgs 
     13from SeismicHandler.modules.messages import MessageSystem as msgs 
    1414from obspy.sh.core import fromUTCDateTime 
    1515 
     
    10011001#msgs.subscribe(__pubmaster, msgs.ALL_TOPICS) 
    10021002 
    1003 def __debug(message, topic=msgs.AUTO_TOPIC): 
    1004     if type(message) == list: 
    1005         message = " ".join(map(str, message)) 
    1006  
    1007     print "%.2f" % time.time(), "[%s]" % topic.getName(), message 
    1008 msgs.subscribe(__debug, 'log.debug') 
    1009  
    10101003def main(): 
    10111004    app = wx.App(False) 
Note: See TracChangeset for help on using the changeset viewer.