1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
|
#!/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://git.immae.eu/releases/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()
|