class Client: def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs self.client_ = APMClient(*args, **kwargs) try: self.client_.capture_message('ping') self.client_._transport.flush() except: self.client_.close() raise ConnectionError("Can't connect to APM-Server") @property def client(self): if self.client_ is None: self.client_ = APMClient(*self.args, **self.kwargs) return self.client_ def close(self): try: self.client_.close() except: pass self.client_ = None def end_transaction(self, name=None, result="", duration=None): try: return self.client.end_transaction(name=name, result=result, duration=duration) except: self.close() return None def begin_transaction(self, transaction_type, trace_parent=None, start=None): try: return self.client.begin_transaction(transaction_type, trace_parent=trace_parent, start=start) except: self.close() return None def capture_exception(self, exc_info=None, handled=True, **kwargs): try: return self.client.capture_exception(exc_info=exc_info, handled=handled, **kwargs) except: self.close() return None def __getattr__(self, item): attr = getattr(self.client, item) return attr
handler = LoggingHandler(client=client) handler.setLevel(logging.WARN) logging.getLogger('elasticapm').setLevel('INFO') LOGGER.addHandler(handler) try: formatter = logging.Formatter('%(asctime)-15s %(levelname)-6s:' '%(message)s') logging.basicConfig(format=formatter, level=logging.INFO) except Exception: client.capture_exception() try: READ_WEBSOCKET_DELAY = 1 # 1 second delay reading from firehose if slack_client.rtm_connect(): LOGGER.info("Bot connected and running!") client.capture_message('connected the bot.') try: while True: command, channel = parse_slack_output( slack_client.rtm_read()) if command and channel: client.begin_transaction(transaction_type='request') handle_command(command, channel) # elasticapm.set_user_context(command=command, channel=channel) client.capture_message('got command') client.end_transaction('processor', 200) # client.begin_transaction('processors',transaction_type='request') time.sleep(READ_WEBSOCKET_DELAY)