#!/usr/bin/python import time import urllib3 import json from systemd import journal urllib3.disable_warnings() http = urllib3.PoolManager() webhook_url = "<%= @slack_logger %>" webhook_username = "<%= @slack_logger_username %>" # These icons are made by CSSCREME.COM # http://csscreme.com/freeicons/ # License: GNU (GENERAL PUBLIC LICENSE) webhook_icon = "https://release.immae.eu/logger.png" priorities = { 0: "0", # black 1: "6684672", # dark dark red 2: "13369344", # dark red 3: "16711680", # red 4: "16737792", # orange 5: "3407616", # green 6: "255", # blue 7: "16777215", # white } def send_to_discord(messages): def send_chunk(chunk, priority, fields=None): data = { "avatar_url": webhook_icon, "username": webhook_username, "embeds": [ { "description": "```\n{}\n```".format(chunk[0:2000]), "color": priorities[priority], "fields": [], } ], } if fields is not None: data["content"] = "@everyone" for field in ["CLIENT_IP", "PATH", "METHOD", "STATUS_CODE", "USER_ID", "FLAG", "LATENCY"]: value = fields.get(field) if value is not None: data["embeds"][-1]["fields"].append({ "name": field.replace("_", " ").capitalize(), "value": value, "inline": True, }) encoded = json.dumps(data).encode('utf-8') r = http.request("POST", webhook_url, headers={'Content-Type': 'application/json'}, body=encoded) if r.status == 429: b = json.loads(r.data) time.sleep(b["retry_after"] / 900) r = http.request("POST", webhook_url, headers={'Content-Type': 'application/json'}, body=encoded) if r.status >= 300: print("Error when sending message: {}".format(r.status)) chunk = "" priority = "" for message in messages: m_priority = int(message.get("PRIORITY", 5)) if m_priority > 6: continue if len(chunk) > 0 and m_priority != priority: send_chunk(chunk, priority) chunk = "" if m_priority <= 4: send_chunk(message["MESSAGE"], m_priority, fields=message) else: priority = m_priority if "SYSLOG_IDENTIFIER" in message: line = "[{}] {}".format(message["SYSLOG_IDENTIFIER"], message["MESSAGE"]) else: line = message["MESSAGE"] if len(line) + len(chunk) > 2000 - 17: send_chunk(chunk, priority) chunk = line else: chunk += "\n" + line if len(chunk) > 0: send_chunk(chunk, priority) j = journal.Reader() j.add_match(_SYSTEMD_UNIT="cryptoportfolio-app.service") j.add_disjunction() j.add_match(UNIT="cryptoportfolio-app.service") j.seek_tail() list(j) while True: lines = list(j) if len(lines) > 0: send_to_discord(lines) time.sleep(5) j.wait()