-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.py
67 lines (51 loc) · 1.84 KB
/
logger.py
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
import logging
from datetime import UTC, datetime
from logging.handlers import RotatingFileHandler
from pathlib import Path
import httpx
import sys_vars
from flask import request
__all__ = ["DiscordHandler", "file_handler", "logger"]
logger = logging.getLogger("linkrot-status")
logger.setLevel(logging.DEBUG)
def _linkrot_formatter(record: logging.LogRecord) -> str:
msg_date = datetime.fromtimestamp(record.created, tz=UTC).strftime("%B %d, %Y @ %I:%M:%S %p")
return f""":warning: Webring Alert :warning:
Alert level: **{record.levelname.capitalize()}**
Date: {msg_date}
Webring URL: {request.root_url}
Link ID: `{record.msg["id"]}`
Link URL: {record.msg["url"]}
Message: {record.msg["message"]}"""
class DiscordHandler(logging.Handler):
"""Create a Discord webhook event handler."""
def __init__(self) -> None:
super().__init__()
self.url = sys_vars.get("DISCORD_WEBHOOK_URL")
def format(self, record: logging.LogRecord) -> dict:
return {"content": _linkrot_formatter(record)}
def emit(self, record: logging.LogRecord) -> logging.LogRecord:
httpx.post(
self.url,
headers={"Content-type": "application/json"},
json=self.format(record),
)
return record
def file_handler(log_name: str, *, linkrot: bool = False) -> RotatingFileHandler:
"""Create a file-based error handler."""
handler = RotatingFileHandler(
Path("log") / log_name,
maxBytes=500_000,
backupCount=5,
delay=True,
)
# Apply the appropriate formatter
if linkrot:
handler.setLevel(logging.DEBUG)
handler.format = _linkrot_formatter
else:
handler.setLevel(logging.ERROR)
handler.setFormatter(
logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s"),
)
return handler