Exemplo n.º 1
0
class Graphdat(object):

    """
    Graphat configuration
    """

    HOST = 'localhost'
    PORT = 26873
    SOCKET_FILE = '/tmp/gd.agent.sock'
    VERSION = '2.3'

    def __init__(self, options):

        # make options into an easy to use dictionary
        options = DotDictionary(options or {})

        # should we enable the graphdat SDK to track requests
        if 'enabled' in options:
            self.enabled = bool(options.enabled)
        else:
            self.enabled = True

        # should graphdat log debugging output
        if 'debug' in options:
            self.debug = bool(options.debug)
        else:
            self.debug = False

        # should graphdat dump the messages being sent to the agent
        if 'messageDump' in options:
            self.messageDump = bool(options.messageDump)
        else:
            self.messageDump = False

        # should graphdat use a preconfigured logger
        self._log = DotDictionary()
        if options.logger:
            self._log.error = options.logger.error
            self._log.info = options.logger.info
        else:
            logging.basicConfig(level='INFO')
            self._log.error = logging.error
            self._log.info = logging.info

        # UDP for Windows and File Socket for Linux
        if sys.platform == 'win32':
            self.socketHost = self.HOST  # host is always localhost
            self.socketPort = options.port or self.PORT
        else:
            self.socketFile = options.socketFile or self.SOCKET_FILE

        self.log("Graphdat (v%s) is %s" % (self.VERSION, self.enabled and 'enabled' or 'disabled'))

        # Create the agent so we can start collecting metrics
        self.agent = Agent(self)

        if self.debug:
            self.log('Graphdat is running in debug mode')
        if self.enabled:
            self.log("Will send to agent on %s" % self.target)

    @property
    def target(self):
        if hasattr(self, 'socketFile') and self.socketFile:
            return self.socketFile
        else:
            return self.socketHost + ':' + str(self.socketPort)

    def add(self, metrics):
        self.agent.add(metrics)

    def log(self, msg, *args, **kwargs):
        if self.debug:
            self._log.info(msg, *args, **kwargs)

    def error(self, msg, *args, **kwargs):
        if self.debug:
            self._log.error(msg)

    def dump(self, msg, *args, **kwargs):
        if self.messageDump:
            self._log.info(msg, *args, **kwargs)