7 Commits
Author SHA1 Message Date
dsql 87835e59b9 release: 1.0.0
first stable release. pre-1.0.0 verification complete: all surviving MED regressions and
gaps resolved and independently re-fired, tree audited clean across the suite.

Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-06 21:21:00 -04:00
dsql 02c17c7e8b fix: cap Action/Actor embed values before wrapping in backticks (no unbalanced markup)
_cap_field truncated the already-backtick-wrapped ('`{action}`') string past 1024 chars,
cutting off the closing backtick so an over-limit field rendered as an unbalanced inline-code
span. it now caps the inner value with reserve=2 (for the two backticks) and wraps after, so
the field stays <=1024 and the backticks are always balanced.

Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-06 17:17:06 -04:00
dsql 4db2a79e0a fix: cap Action/Actor embed field values to discord's 1024-char limit (dpylogger-8)
The 1024-char cap + empty substitute only ever applied to the Log field.
Action and Actor got no cap, so a long action/actor string (a real path -
e.g. a long command invocation string as the action) triggers Discord's
BASE_TYPE_MAX_LENGTH 400 on send; _send swallows that via log.exception and
returns None, silently losing the Discord message while the stdlib mirror
survives. Route all three fields through one _cap_field helper (single
source for the 1024 constant) instead of duplicating the cap logic.

Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-06 00:11:40 -04:00
dsql 262477d193 fix: chain the KeyError->ValueError normalization with from error (dpylogger-10)
The settings-lookup KeyError->ValueError raise was bare, unlike the three
sibling discord-exception normalization sites which all chain via
"from error". __context__ still linked implicitly at runtime, but this makes
the traceback style consistent (flake8-B904) across every normalization site.

Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-06 00:11:26 -04:00
dsql 8bba9dde05 fix: check channel type before the guild-derivation guard (dpylogger-9)
The wrong-type channel check sat after the no-resolvable-guild guard, so a
non-TextChannel object passed without a guild raised the misleading "channel
provided without a resolvable guild" instead of "is not a text channel" - the
accurate message only fired when a guild was also supplied. Move the type
check first so both branches report the real problem.

Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-06 00:11:05 -04:00
dsql 4e2ba00120 refactor: derive __version__ from package metadata (single source)
Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-03 16:59:09 -04:00
dsql 63d9ed10d3 docs: compress prose/module docstrings, em-dash->hyphen (de-bloat wave 1)
Signed-off-by: disqualifier <dev@disqualifier.me>
2026-07-03 00:12:44 -04:00
4 changed files with 45 additions and 48 deletions
+3 -3
View File
@@ -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@v0.1.7
``` ```
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@v0.1.7"
``` ```
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 `@v0.1.7` suffix from the line above to install the latest unpinned.
## Usage ## Usage
+1 -1
View File
@@ -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 = [
+8 -1
View File
@@ -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__"]
+33 -43
View File
@@ -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)