Compare commits
7
Commits
1c5d42e4f0
..
v1.0.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d21de01ada | ||
|
|
02c17c7e8b | ||
|
|
4db2a79e0a | ||
|
|
262477d193 | ||
|
|
8bba9dde05 | ||
|
|
4e2ba00120 | ||
|
|
63d9ed10d3 |
@@ -10,18 +10,18 @@ live from `bot.settings` so it can change at runtime via a command.
|
|||||||
`requirements.txt`:
|
`requirements.txt`:
|
||||||
|
|
||||||
```
|
```
|
||||||
dpy_logger @ git+ssh://git@git.rethinkstudios.io/rethink-public/dpy_logger.git@v0.1.6
|
dpy_logger @ git+ssh://git@git.rethinkstudios.io/rethink-public/dpy_logger.git@v1.0.0
|
||||||
```
|
```
|
||||||
|
|
||||||
Direct:
|
Direct:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pip install "dpy_logger @ git+ssh://git@git.rethinkstudios.io/rethink-public/dpy_logger.git@v0.1.6"
|
pip install "dpy_logger @ git+ssh://git@git.rethinkstudios.io/rethink-public/dpy_logger.git@v1.0.0"
|
||||||
```
|
```
|
||||||
|
|
||||||
Requires `discord.py` (pulled transitively).
|
Requires `discord.py` (pulled transitively).
|
||||||
|
|
||||||
Drop the `@v0.1.6` suffix from the line above to install the latest unpinned.
|
Drop the `@v1.0.0` suffix from the line above to install the latest unpinned.
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "dpy_logger"
|
name = "dpy_logger"
|
||||||
version = "0.1.6"
|
version = "1.0.0"
|
||||||
description = "Leveled Discord channel logger for discord.py — config-free, injectable, installable."
|
description = "Leveled Discord channel logger for discord.py — config-free, injectable, installable."
|
||||||
requires-python = ">=3.10"
|
requires-python = ">=3.10"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
|||||||
@@ -1,3 +1,10 @@
|
|||||||
|
from importlib.metadata import version, PackageNotFoundError
|
||||||
|
|
||||||
from .dpy_logger import DPYLogger, DEFAULT_COLORS
|
from .dpy_logger import DPYLogger, DEFAULT_COLORS
|
||||||
|
|
||||||
__all__ = ["DPYLogger", "DEFAULT_COLORS"]
|
try:
|
||||||
|
__version__ = version("dpy_logger")
|
||||||
|
except PackageNotFoundError:
|
||||||
|
__version__ = "0.0.0+unknown"
|
||||||
|
|
||||||
|
__all__ = ["DPYLogger", "DEFAULT_COLORS", "__version__"]
|
||||||
|
|||||||
@@ -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.initialize() # resolves ids -> objects
|
||||||
await bot.log.success("user promoted", action="promote", actor=ctx.author)
|
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
|
dual sink: every call also mirrors to the stdlib logger (getLogger(__name__))
|
||||||
channel via bot.settings[guild.id]['channels']['logs']; omit it to use the
|
before the discord send, so the record survives even if discord fails. set
|
||||||
construction channel.
|
log_to_file=False at construction, or per call, to disable.
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
errors: setup raises, sends swallow. resolution failures (unresolvable
|
errors: setup raises, sends swallow. resolution failures (unresolvable
|
||||||
guild/channel, bad config, a non-text channel, an invalid timezone) raise
|
guild/channel, bad config, a non-text channel, an invalid timezone) raise
|
||||||
ValueError from `initialize()`. underlying discord exceptions (NotFound/
|
ValueError from `initialize()`, with underlying discord exceptions normalized
|
||||||
Forbidden/HTTPException/InvalidData and other ClientException subclasses)
|
to it. per-call send failures never propagate - they fall back to the stdlib
|
||||||
are normalized to that same ValueError. on a per-call send, resolution and
|
logger so a transient discord failure never breaks the caller's command.
|
||||||
send failures never propagate — they fall back to the stdlib logger so a
|
|
||||||
transient discord failure never breaks the caller's command.
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
@@ -63,6 +54,7 @@ DEFAULT_COLORS = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
DISCORD_CONTENT_LIMIT = 2000
|
DISCORD_CONTENT_LIMIT = 2000
|
||||||
|
DISCORD_FIELD_VALUE_LIMIT = 1024
|
||||||
|
|
||||||
LEVEL_MAP = {
|
LEVEL_MAP = {
|
||||||
"debug": logging.DEBUG,
|
"debug": logging.DEBUG,
|
||||||
@@ -114,16 +106,12 @@ class DPYLogger:
|
|||||||
if not self.guild:
|
if not self.guild:
|
||||||
raise ValueError(f"[dpy_logger] cannot resolve channel {self.channel} without a guild")
|
raise ValueError(f"[dpy_logger] cannot resolve channel {self.channel} without a guild")
|
||||||
self.channel = await self._get_channel(self.guild)
|
self.channel = await self._get_channel(self.guild)
|
||||||
# a channel with no guild would otherwise blackout every send silently; derive
|
if self.channel is not None and not isinstance(self.channel, (discord.TextChannel, int)):
|
||||||
# the guild from it, or fail loud here rather than later
|
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):
|
if self.guild is None and isinstance(self.channel, discord.TextChannel):
|
||||||
self.guild = self.channel.guild
|
self.guild = self.channel.guild
|
||||||
if self.guild is None and self.channel is not None:
|
if self.guild is None and self.channel is not None:
|
||||||
raise ValueError("[dpy_logger] channel provided without a resolvable guild")
|
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):
|
async def _get_guild(self, guild):
|
||||||
"""resolve a guild from id-or-object, raising if unresolvable"""
|
"""resolve a guild from id-or-object, raising if unresolvable"""
|
||||||
@@ -162,8 +150,8 @@ class DPYLogger:
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
channel_id = self.bot.settings[guild.id]["channels"]["logs"]
|
channel_id = self.bot.settings[guild.id]["channels"]["logs"]
|
||||||
except KeyError:
|
except KeyError as error:
|
||||||
raise ValueError(f"[dpy_logger] no log channel configured for guild {guild.id}")
|
raise ValueError(f"[dpy_logger] no log channel configured for guild {guild.id}") from error
|
||||||
try:
|
try:
|
||||||
channel = await guild.fetch_channel(channel_id)
|
channel = await guild.fetch_channel(channel_id)
|
||||||
except (discord.HTTPException, discord.ClientException) as error:
|
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")
|
raise ValueError(f"[dpy_logger] configured channel {channel_id} is not a text channel")
|
||||||
return 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):
|
def build_embed(self, level, action, actor, details):
|
||||||
"""build the embed for a log call
|
"""build the embed for a log call
|
||||||
|
|
||||||
@@ -183,16 +180,14 @@ class DPYLogger:
|
|||||||
if self._embed_builder is not None:
|
if self._embed_builder is not None:
|
||||||
return self._embed_builder(self, level, action, actor, details)
|
return self._embed_builder(self, level, action, actor, details)
|
||||||
em = discord.Embed(color=self.colors[level])
|
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) != "":
|
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) != "":
|
if actor is not None and str(actor) != "":
|
||||||
em.add_field(name="Actor", value=f"`{actor}`", inline=True)
|
em.add_field(name="Actor", value=f"`{self._cap_field(str(actor), reserve=2)}`", inline=True)
|
||||||
# discord 400s an empty or >1024-char field value; substitute + cap
|
|
||||||
log_value = str(details) if details is not None and str(details) != "" else "(no message)"
|
log_value = str(details) if details is not None and str(details) != "" else "(no message)"
|
||||||
if len(log_value) > 1024:
|
em.add_field(name="Log", value=self._cap_field(log_value), inline=False)
|
||||||
log_value = log_value[:1021] + "..."
|
|
||||||
em.add_field(name="Log", value=log_value, inline=False)
|
|
||||||
em.timestamp = datetime.now(self.timezone)
|
em.timestamp = datetime.now(self.timezone)
|
||||||
em.set_footer(text=f"{self.footer} Logging".strip(), icon_url=self.avatar)
|
em.set_footer(text=f"{self.footer} Logging".strip(), icon_url=self.avatar)
|
||||||
return em
|
return em
|
||||||
@@ -209,12 +204,7 @@ class DPYLogger:
|
|||||||
|
|
||||||
async def _send(self, level, log_msg, action=None, actor=None, guild=None,
|
async def _send(self, level, log_msg, action=None, actor=None, guild=None,
|
||||||
log_to_file=None, content=None):
|
log_to_file=None, content=None):
|
||||||
"""resolve channel and dispatch a leveled embed; mirror to stdlib unless opted out
|
"""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.
|
|
||||||
"""
|
|
||||||
if self.log_to_file if log_to_file is None else log_to_file:
|
if self.log_to_file if log_to_file is None else log_to_file:
|
||||||
self._emit_stdlib(level, action, actor, log_msg)
|
self._emit_stdlib(level, action, actor, log_msg)
|
||||||
try:
|
try:
|
||||||
@@ -248,7 +238,7 @@ class DPYLogger:
|
|||||||
async def task(self, log, action=None, actor=None, guild=None, log_to_file=None):
|
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
|
"""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
|
always attributed to SYSTEM/TASK regardless of the caller-supplied actor
|
||||||
"""
|
"""
|
||||||
return await self._send("task", log, action, "SYSTEM/TASK", guild, log_to_file)
|
return await self._send("task", log, action, "SYSTEM/TASK", guild, log_to_file)
|
||||||
|
|||||||
Reference in New Issue
Block a user