PageRenderTime 11ms CodeModel.GetById 2ms app.highlight 7ms RepoModel.GetById 1ms app.codeStats 0ms

/mysql_watcher/indra/base/metrics.py

https://bitbucket.org/lindenlab/apiary/
Python | 121 lines | 110 code | 0 blank | 11 comment | 0 complexity | dcdd201212fbf187cdef89da26b66510 MD5 | raw file
  1"""\
  2@file metrics.py
  3@author Phoenix
  4@date 2007-11-27
  5@brief simple interface for logging metrics
  6
  7$LicenseInfo:firstyear=2007&license=mit$
  8
  9Copyright (c) 2007-2010, Linden Research, Inc.
 10
 11Permission is hereby granted, free of charge, to any person obtaining a copy
 12of this software and associated documentation files (the "Software"), to deal
 13in the Software without restriction, including without limitation the rights
 14to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 15copies of the Software, and to permit persons to whom the Software is
 16furnished to do so, subject to the following conditions:
 17
 18The above copyright notice and this permission notice shall be included in
 19all copies or substantial portions of the Software.
 20
 21THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 22IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 23FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 24AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 25LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 26OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 27THE SOFTWARE.
 28$/LicenseInfo$
 29"""
 30
 31import sys
 32try:
 33    import syslog
 34except ImportError:
 35    # Windows
 36    import sys
 37    class syslog(object):
 38        # wrap to a lame syslog for windows
 39        _logfp = sys.stderr
 40        def syslog(msg):
 41            _logfp.write(msg)
 42            if not msg.endswith('\n'):
 43                _logfp.write('\n')
 44        syslog = staticmethod(syslog)
 45
 46from indra.base.llsd import format_notation
 47
 48def record_metrics(table, stats):
 49    "Write a standard metrics log"
 50    _log("LLMETRICS", table, stats)
 51
 52def record_event(table, data):
 53    "Write a standard logmessage log"
 54    _log("LLLOGMESSAGE", table, data)
 55
 56def set_destination(dest):
 57    """Set the destination of metrics logs for this process.
 58
 59    If you do not call this function prior to calling a logging
 60    method, that function will open sys.stdout as a destination.
 61    Attempts to set dest to None will throw a RuntimeError.
 62    @param dest a file-like object which will be the destination for logs."""
 63    if dest is None:
 64        raise RuntimeError("Attempt to unset metrics destination.")
 65    global _destination
 66    _destination = dest
 67
 68def destination():
 69    """Get the destination of the metrics logs for this process.
 70    Returns None if no destination is set"""
 71    global _destination
 72    return _destination
 73
 74class SysLogger(object):
 75    "A file-like object which writes to syslog."
 76    def __init__(self, ident='indra', logopt = None, facility = None):
 77        try:
 78            if logopt is None:
 79                logopt = syslog.LOG_CONS | syslog.LOG_PID
 80            if facility is None:
 81                facility = syslog.LOG_LOCAL0
 82            syslog.openlog(ident, logopt, facility)
 83            import atexit
 84            atexit.register(syslog.closelog)
 85        except AttributeError:
 86            # No syslog module on Windows
 87            pass
 88
 89    def write(str):
 90        syslog.syslog(str)
 91    write = staticmethod(write)
 92
 93    def flush():
 94        pass
 95    flush = staticmethod(flush)
 96
 97#
 98# internal API
 99#
100_sequence_id = 0
101_destination = None
102
103def _next_id():
104    global _sequence_id
105    next = _sequence_id
106    _sequence_id += 1
107    return next
108
109def _dest():
110    global _destination
111    if _destination is None:
112        # this default behavior is documented in the metrics functions above.
113        _destination = sys.stdout
114    return _destination
115    
116def _log(header, table, data):
117    log_line = "%s (%d) %s %s" \
118               % (header, _next_id(), table, format_notation(data))
119    dest = _dest()
120    dest.write(log_line)
121    dest.flush()