]> git.immae.eu Git - perso/Immae/Projets/Puppet.git/blame - modules/role/templates/cryptoportfolio/api_logger.py.erb
Add logger username
[perso/Immae/Projets/Puppet.git] / modules / role / templates / cryptoportfolio / api_logger.py.erb
CommitLineData
6b95d3bd
IB
1#!/usr/bin/python
2
3import time
4import urllib3
5import json
6from systemd import journal
7
8urllib3.disable_warnings()
9http = urllib3.PoolManager()
10
11webhook_url = "<%= @slack_logger %>"
123ee097 12webhook_username = "<%= @slack_logger_username %>"
6b95d3bd
IB
13webhook_icon = "https://git.immae.eu/releases/logger.png"
14
15def send_to_discord(message):
16 def send_chunk(chunk):
17 data = {
18 "avatar_url": webhook_icon,
123ee097 19 "username": webhook_username,
6b95d3bd
IB
20 "content": "```\n{}\n```".format(chunk),
21 }
22 encoded = json.dumps(data).encode('utf-8')
23
24 r = http.request("POST", webhook_url,
25 headers={'Content-Type': 'application/json'},
26 body=encoded)
27 if r.status == 429:
28 b = json.loads(r.data)
29 time.sleep(b["retry_after"] / 900)
30 r = http.request("POST", webhook_url,
31 headers={'Content-Type': 'application/json'},
32 body=encoded)
33 assert r.status < 299
34
35 chunk = ""
36 for line in message.split("\n"):
37 if len(line) + len(chunk) > 2000 - 17:
38 send_chunk(chunk)
39 chunk = line
40 else:
41 chunk += "\n" + line
42 send_chunk(chunk)
43
44j = journal.Reader()
45j.add_match(_SYSTEMD_UNIT="cryptoportfolio-app.service")
46j.seek_tail()
47list(j)
48
49while True:
50 lines = [entry["MESSAGE"] for entry in list(j)]
51 if len(lines) > 0:
52 send_to_discord("\n".join(lines))
53 time.sleep(3)