Commits

Josh VanderLinden committed 242b41e

Comments (0)

Files changed (1)

+"""
+RethinkLog - Log messages to a rethinkdb instance.
+
+Copyright (C) 2013 Josh VanderLinden <arch@cloudlery.com>
+
+Date: 2013-02-07
+Version: 0.0.1
+
+"""
+
+from collections import deque
+
+from rethinkdb import r
+
+from weechat import buffer_get_string as get, config_get_plugin as cfg
+import weechat
+
+__name__ = 'RethinkLog'
+__author__ = 'codekoala'
+__version__ = '0.0.1'
+__license__ = 'MIT'
+__description__ = 'Log messages to a RethinkDB cluster'
+
+
+weechat.register(__name__, __author__, __version__, __license__, __description__, '', '')
+
+
+defaults = dict(
+    host='localhost',
+    port='28015',
+    db='weechat',
+    table='messages',
+)
+
+# initialize config
+for o, v in defaults.items():
+    if not cfg(o):
+        weechat.config_set_plugin(o, v)
+
+
+class RethinkLogger(object):
+    """Log messages to a RethinkDB cluster"""
+
+    def __init__(self):
+        self.cnx = None
+        self.queue = deque()
+
+    @property
+    def r(self):
+        if self.cnx is None:
+            self.cnx = r.connect(cfg('host'), int(cfg('port')))
+
+        return r.db(cfg('db')).table(cfg('table'))
+
+    def log(self, data, buf, time, tags, display, hilight, prefix, msg):
+        buffer_name = get(buf, 'short_name') or get(buf, 'name')
+
+        record = dict(
+            data=data.strip(),
+            buffer=buffer_name.strip(),
+            timestamp=int(time),
+            tags=[t.strip() for t in tags.split(',') if t],
+            display=bool(int(display)),
+            hilight=bool(int(hilight)),
+            prefix=prefix.strip(),
+            message=msg.strip().decode('utf-8')
+        )
+
+        self.queue.append(record)
+
+        return weechat.WEECHAT_RC_OK
+
+    def flush(self, data, remaining_calls):
+        """Send multiple records to RethinkDB at one time"""
+
+        return_code = weechat.WEECHAT_RC_OK
+
+        while True:
+            try:
+                record = self.queue.popleft()
+            except IndexError:
+                break
+
+            try:
+                self.r.insert(record).run()
+            except Exception as e:
+                self.queue.appendleft(record)
+                weechat.prnt('', 'Failed to log messages to rethinkdb: %s' % str(e))
+                return_code = weechat.WEECHAT_RC_ERROR
+                break
+
+        return return_code
+
+
+plugin = RethinkLogger()
+log = plugin.log
+flush = plugin.flush
+
+weechat.hook_print('', '', '', 1, 'log', '')
+weechat.hook_timer(5000, 0, 0, 'flush', '')