|
|
|
@@ -19,31 +19,22 @@ read live from bot.settings at call time (no restart needed).
|
|
|
|
|
await bot.log.initialize() # resolves ids -> objects
|
|
|
|
|
await bot.log.success("user promoted", action="promote", actor=ctx.author)
|
|
|
|
|
|
|
|
|
|
levels: debug, info, success, fail (alias failure), task, critical.
|
|
|
|
|
levels: debug, info, success, fail (alias failure), task, critical. a per-call
|
|
|
|
|
guild= argument routes to that guild's bot.settings[guild.id]['channels']['logs']
|
|
|
|
|
instead of the construction channel. pass embed_builder=fn(logger, level, action,
|
|
|
|
|
actor, details) -> discord.Embed to restyle without subclassing, or override
|
|
|
|
|
build_embed in a subclass for complex cases. no feed/announcement method by
|
|
|
|
|
design; subclass and reuse _resolve for project-specific log types.
|
|
|
|
|
|
|
|
|
|
dynamic routing: a per-call guild= argument logs to that guild's configured
|
|
|
|
|
channel via bot.settings[guild.id]['channels']['logs']; omit it to use the
|
|
|
|
|
construction channel.
|
|
|
|
|
|
|
|
|
|
custom embeds: pass embed_builder=fn(logger, level, action, actor, details)
|
|
|
|
|
-> discord.Embed to restyle without subclassing; every level routes through
|
|
|
|
|
it. for complex cases override build_embed in a subclass instead.
|
|
|
|
|
|
|
|
|
|
dual sink: every call also mirrors to the stdlib logger (getLogger(__name__));
|
|
|
|
|
the stdlib emit happens before the discord send, so the record survives even
|
|
|
|
|
if discord fails. set log_to_file=False at construction, or per call, to
|
|
|
|
|
disable.
|
|
|
|
|
|
|
|
|
|
extending: no feed/announcement method by design; subclass and reuse
|
|
|
|
|
_resolve for project-specific log types.
|
|
|
|
|
dual sink: every call also mirrors to the stdlib logger (getLogger(__name__))
|
|
|
|
|
before the discord send, so the record survives even if discord fails. set
|
|
|
|
|
log_to_file=False at construction, or per call, to disable.
|
|
|
|
|
|
|
|
|
|
errors: setup raises, sends swallow. resolution failures (unresolvable
|
|
|
|
|
guild/channel, bad config, a non-text channel, an invalid timezone) raise
|
|
|
|
|
ValueError from `initialize()`. underlying discord exceptions (NotFound/
|
|
|
|
|
Forbidden/HTTPException/InvalidData and other ClientException subclasses)
|
|
|
|
|
are normalized to that same ValueError. on a per-call send, resolution and
|
|
|
|
|
send failures never propagate — they fall back to the stdlib logger so a
|
|
|
|
|
transient discord failure never breaks the caller's command.
|
|
|
|
|
ValueError from `initialize()`, with underlying discord exceptions normalized
|
|
|
|
|
to it. per-call send failures never propagate - they fall back to the stdlib
|
|
|
|
|
logger so a transient discord failure never breaks the caller's command.
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
import logging
|
|
|
|
@@ -63,6 +54,7 @@ DEFAULT_COLORS = {
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
DISCORD_CONTENT_LIMIT = 2000
|
|
|
|
|
DISCORD_FIELD_VALUE_LIMIT = 1024
|
|
|
|
|
|
|
|
|
|
LEVEL_MAP = {
|
|
|
|
|
"debug": logging.DEBUG,
|
|
|
|
@@ -114,16 +106,12 @@ class DPYLogger:
|
|
|
|
|
if not self.guild:
|
|
|
|
|
raise ValueError(f"[dpy_logger] cannot resolve channel {self.channel} without a guild")
|
|
|
|
|
self.channel = await self._get_channel(self.guild)
|
|
|
|
|
# a channel with no guild would otherwise blackout every send silently; derive
|
|
|
|
|
# the guild from it, or fail loud here rather than later
|
|
|
|
|
if self.channel is not None and not isinstance(self.channel, (discord.TextChannel, int)):
|
|
|
|
|
raise ValueError(f"[dpy_logger] channel {self.channel!r} is not a text channel")
|
|
|
|
|
if self.guild is None and isinstance(self.channel, discord.TextChannel):
|
|
|
|
|
self.guild = self.channel.guild
|
|
|
|
|
if self.guild is None and self.channel is not None:
|
|
|
|
|
raise ValueError("[dpy_logger] channel provided without a resolvable guild")
|
|
|
|
|
# a wrong-type channel object (Thread/VoiceChannel/ForumChannel) would also pass
|
|
|
|
|
# silently and misroute/blackhole later; fail loud here instead
|
|
|
|
|
if self.channel is not None and not isinstance(self.channel, (discord.TextChannel, int)):
|
|
|
|
|
raise ValueError(f"[dpy_logger] channel {self.channel!r} is not a text channel")
|
|
|
|
|
|
|
|
|
|
async def _get_guild(self, guild):
|
|
|
|
|
"""resolve a guild from id-or-object, raising if unresolvable"""
|
|
|
|
@@ -162,8 +150,8 @@ class DPYLogger:
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
channel_id = self.bot.settings[guild.id]["channels"]["logs"]
|
|
|
|
|
except KeyError:
|
|
|
|
|
raise ValueError(f"[dpy_logger] no log channel configured for guild {guild.id}")
|
|
|
|
|
except KeyError as error:
|
|
|
|
|
raise ValueError(f"[dpy_logger] no log channel configured for guild {guild.id}") from error
|
|
|
|
|
try:
|
|
|
|
|
channel = await guild.fetch_channel(channel_id)
|
|
|
|
|
except (discord.HTTPException, discord.ClientException) as error:
|
|
|
|
@@ -172,6 +160,15 @@ class DPYLogger:
|
|
|
|
|
raise ValueError(f"[dpy_logger] configured channel {channel_id} is not a text channel")
|
|
|
|
|
return channel
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def _cap_field(value: str, reserve: int = 0) -> str:
|
|
|
|
|
"""cap a value to discord's 1024-char field limit (less `reserve` chars for any wrapping
|
|
|
|
|
the caller adds around it, e.g. backticks), truncating with an ellipsis"""
|
|
|
|
|
limit = DISCORD_FIELD_VALUE_LIMIT - reserve
|
|
|
|
|
if len(value) > limit:
|
|
|
|
|
return value[:limit - 3] + "..."
|
|
|
|
|
return value
|
|
|
|
|
|
|
|
|
|
def build_embed(self, level, action, actor, details):
|
|
|
|
|
"""build the embed for a log call
|
|
|
|
|
|
|
|
|
@@ -183,16 +180,14 @@ class DPYLogger:
|
|
|
|
|
if self._embed_builder is not None:
|
|
|
|
|
return self._embed_builder(self, level, action, actor, details)
|
|
|
|
|
em = discord.Embed(color=self.colors[level])
|
|
|
|
|
# is-not-None keeps falsy-but-valid values (0, False) rendering
|
|
|
|
|
# discord 400s an empty or >1024-char field value; cap then wrap so the closing
|
|
|
|
|
# backtick is never truncated off (cap the inner value, accounting for the 2 backticks)
|
|
|
|
|
if action is not None and str(action) != "":
|
|
|
|
|
em.add_field(name="Action", value=f"`{action}`", inline=True)
|
|
|
|
|
em.add_field(name="Action", value=f"`{self._cap_field(str(action), reserve=2)}`", inline=True)
|
|
|
|
|
if actor is not None and str(actor) != "":
|
|
|
|
|
em.add_field(name="Actor", value=f"`{actor}`", inline=True)
|
|
|
|
|
# discord 400s an empty or >1024-char field value; substitute + cap
|
|
|
|
|
em.add_field(name="Actor", value=f"`{self._cap_field(str(actor), reserve=2)}`", inline=True)
|
|
|
|
|
log_value = str(details) if details is not None and str(details) != "" else "(no message)"
|
|
|
|
|
if len(log_value) > 1024:
|
|
|
|
|
log_value = log_value[:1021] + "..."
|
|
|
|
|
em.add_field(name="Log", value=log_value, inline=False)
|
|
|
|
|
em.add_field(name="Log", value=self._cap_field(log_value), inline=False)
|
|
|
|
|
em.timestamp = datetime.now(self.timezone)
|
|
|
|
|
em.set_footer(text=f"{self.footer} Logging".strip(), icon_url=self.avatar)
|
|
|
|
|
return em
|
|
|
|
@@ -209,12 +204,7 @@ class DPYLogger:
|
|
|
|
|
|
|
|
|
|
async def _send(self, level, log_msg, action=None, actor=None, guild=None,
|
|
|
|
|
log_to_file=None, content=None):
|
|
|
|
|
"""resolve channel and dispatch a leveled embed; mirror to stdlib unless opted out
|
|
|
|
|
|
|
|
|
|
stdlib emit happens first so the record survives a failed discord send, which
|
|
|
|
|
falls back to stdlib rather than propagating. `content` carries the critical-level
|
|
|
|
|
ping/@here text (None for other levels), so every level shares this one contract.
|
|
|
|
|
"""
|
|
|
|
|
"""resolve channel and dispatch a leveled embed; mirror to stdlib unless opted out"""
|
|
|
|
|
if self.log_to_file if log_to_file is None else log_to_file:
|
|
|
|
|
self._emit_stdlib(level, action, actor, log_msg)
|
|
|
|
|
try:
|
|
|
|
@@ -223,8 +213,11 @@ class DPYLogger:
|
|
|
|
|
content=content,
|
|
|
|
|
embed=self.build_embed(level, action, actor, log_msg),
|
|
|
|
|
)
|
|
|
|
|
except Exception:
|
|
|
|
|
_log.exception(f"[dpy_logger] failed to send {level} log: {log_msg}")
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
# WARNING, not ERROR: the record was already mirrored to the stdlib sink BEFORE the
|
|
|
|
|
# send (see _emit_stdlib above), so a swallowed discord-send failure is recovered
|
|
|
|
|
# cleanly - the log survives, only the channel mirror was lost. lazy interpolation.
|
|
|
|
|
_log.warning("[dpy_logger] failed to send %s log: %s (%s)", level, log_msg, exc)
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
async def debug(self, log, action=None, actor=None, guild=None, log_to_file=None):
|
|
|
|
@@ -248,7 +241,7 @@ class DPYLogger:
|
|
|
|
|
async def task(self, log, action=None, actor=None, guild=None, log_to_file=None):
|
|
|
|
|
"""log a task-level message with SYSTEM/TASK as the actor
|
|
|
|
|
|
|
|
|
|
actor is accepted for caller compatibility and ignored — task actions are
|
|
|
|
|
actor is accepted for caller compatibility and ignored - task actions are
|
|
|
|
|
always attributed to SYSTEM/TASK regardless of the caller-supplied actor
|
|
|
|
|
"""
|
|
|
|
|
return await self._send("task", log, action, "SYSTEM/TASK", guild, log_to_file)
|
|
|
|
|