rewrite: Add base context ContextVar.

This commit is contained in:
2022-11-07 16:08:27 +02:00
parent 872e5fd71f
commit 3445bdff3e
4 changed files with 118 additions and 12 deletions

51
bot/meta/context.py Normal file
View File

@@ -0,0 +1,51 @@
from contextvars import ContextVar
class Context:
__slots__ = (
'bot',
'interaction', 'message',
'guild', 'channel', 'author', 'user'
)
def __init__(self, **kwargs):
self.bot = kwargs.pop('bot', None)
self.interaction = interaction = kwargs.pop('interaction', None)
self.message = message = kwargs.pop('message', interaction.message if interaction is not None else None)
guild = kwargs.pop('guild', None)
channel = kwargs.pop('channel', None)
author = kwargs.pop('author', None)
if message is not None:
guild = guild or message.guild
channel = channel or message.channel
author = author or message.author
elif interaction is not None:
guild = guild or interaction.guild
channel = channel or interaction.channel
author = author or interaction.user
self.guild = guild
self.channel = channel
self.author = self.user = author
def log_string(self):
"""Markdown formatted summary for live logging."""
parts = []
if self.interaction is not None:
parts.append(f"<int id={self.interaction.id} type={self.interaction.type.name}>")
if self.message is not None:
parts.append(f"<msg id={self.message.id}>")
if self.author is not None:
parts.append(f"<user id={self.author.id} name='{self.author.name}'>")
if self.channel is not None:
parts.append(f"<chan id={self.channel.id} name='{self.channel.name}'>")
if self.guild is not None:
parts.append(f"<guild id={self.guild.id} name='{self.guild.name}'>")
return " ".join(parts)
context = ContextVar('context', default=Context())

View File

@@ -7,12 +7,13 @@ from contextlib import contextmanager
from io import StringIO
from contextvars import ContextVar
from discord import AllowedMentions, Webhook, File
from discord import Webhook, File
import aiohttp
from .config import conf
from . import sharding
from utils.lib import split_text, utc_now
from .context import context
from utils.lib import utc_now
log_context: ContextVar[str] = ContextVar('logging_context', default='CTX: ROOT CONTEXT')
@@ -41,6 +42,7 @@ BOLD_SEQ = "\033[1m"
"]]]"
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
def colour_escape(fmt: str) -> str:
cmap = {
'%(black)': COLOR_SEQ % BLACK,
@@ -94,6 +96,7 @@ class ContextInjection(logging.Filter):
if not hasattr(record, 'action'):
record.action = log_action.get()
record.app = log_app.get()
record.ctx = context.get().log_string()
return True
@@ -149,8 +152,9 @@ class WebHookHandler(logging.StreamHandler):
async def post(self, record):
try:
timestamp = utc_now().strftime("%d/%m/%Y, %H:%M:%S")
header = f"[{timestamp}][{record.levelname}][{record.app}][{record.action}][{record.context}]\n"
message = header+record.msg
header = f"[{timestamp}][{record.levelname}][{record.app}][{record.action}][{record.context}]"
context = f"\n# Context: {record.ctx}" if record.ctx else ""
message = f"{header}\n{record.msg}{context}"
if len(message) > 1900:
as_file = True