mirror of
https://github.com/Cog-Creators/Red-DiscordBot.git
synced 2025-11-20 09:56:05 -05:00
[Core] Rich logging for not so rich people (#4577)
* Pop stash * add rich to setup * Added forceful enabling of rich logging * revert some unintended pushed * Fix possible unbound var Fix possible 0 members w/out members intent * One day I won't forget to do style passes * So this is a thing apperently... * Bump rich to 9.5.1 * Lock secondary deps * Different stuff, see the full commit description for more info - Change few things from print to log.info - put the log handlers on the root logger instead of individual loggers - capture warnings to a logger * Modify log handler to show logger name * Add a Triboolian to force disable rich * Style checks * shortened time, added logger name... again. * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa * Style & linking * Be or not to be? Whatever man, it's 4:30 in the morning, goto sleep >.< * Reintroduce outdated message. Co-authored-by: jack1142 <6032823+jack1142@users.noreply.github.com>
This commit is contained in:
@@ -29,6 +29,7 @@ from typing import (
|
||||
overload,
|
||||
)
|
||||
from types import MappingProxyType
|
||||
from rich.console import Console
|
||||
|
||||
import discord
|
||||
from discord.ext import commands as dpy_commands
|
||||
@@ -221,6 +222,9 @@ class RedBase(
|
||||
|
||||
self._deletion_requests: MutableMapping[int, asyncio.Lock] = weakref.WeakValueDictionary()
|
||||
|
||||
# Although I see the use of keeping this public, lets rather make it private.
|
||||
self._rich_console = Console()
|
||||
|
||||
def set_help_formatter(self, formatter: commands.help.HelpFormatterABC):
|
||||
"""
|
||||
Set's Red's help formatter.
|
||||
@@ -878,7 +882,7 @@ class RedBase(
|
||||
packages.insert(0, "permissions")
|
||||
|
||||
to_remove = []
|
||||
print("Loading packages...")
|
||||
log.info("Loading packages...")
|
||||
for package in packages:
|
||||
try:
|
||||
spec = await self._cog_mgr.find_cog(package)
|
||||
@@ -901,7 +905,7 @@ class RedBase(
|
||||
for package in to_remove:
|
||||
packages.remove(package)
|
||||
if packages:
|
||||
print("Loaded packages: " + ", ".join(packages))
|
||||
log.info("Loaded packages: " + ", ".join(packages))
|
||||
|
||||
if self.rpc_enabled:
|
||||
await self.rpc.initialize(self.rpc_port)
|
||||
|
||||
@@ -249,6 +249,20 @@ def parse_cli_flags(args):
|
||||
" to see what each intent does.\n"
|
||||
"This flag can be used multiple times to specify multiple intents.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--force-rich-logging",
|
||||
action="store_true",
|
||||
dest="rich_logging",
|
||||
default=None,
|
||||
help="Forcefully enables the Rich logging handlers. This is normally enabled for supported active terminals.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--force-disable-rich-logging",
|
||||
action="store_false",
|
||||
dest="rich_logging",
|
||||
default=None,
|
||||
help="Forcefully disables the Rich logging handlers.",
|
||||
)
|
||||
|
||||
args = parser.parse_args(args)
|
||||
|
||||
|
||||
@@ -33,10 +33,15 @@ from .utils._internal_utils import (
|
||||
)
|
||||
from .utils.chat_formatting import inline, bordered, format_perms_list, humanize_timedelta
|
||||
|
||||
from rich.table import Table
|
||||
from rich.columns import Columns
|
||||
from rich.panel import Panel
|
||||
from rich.text import Text
|
||||
|
||||
log = logging.getLogger("red")
|
||||
init()
|
||||
|
||||
INTRO = r"""
|
||||
INTRO = r"""[red]
|
||||
______ _ ______ _ _ ______ _
|
||||
| ___ \ | | | _ (_) | | | ___ \ | |
|
||||
| |_/ /___ __| | ______ | | | |_ ___ ___ ___ _ __ __| | | |_/ / ___ | |_
|
||||
@@ -52,7 +57,7 @@ def init_events(bot, cli_flags):
|
||||
@bot.event
|
||||
async def on_connect():
|
||||
if bot._uptime is None:
|
||||
print("Connected to Discord. Getting ready...")
|
||||
log.info("Connected to Discord. Getting ready...")
|
||||
|
||||
@bot.event
|
||||
async def on_ready():
|
||||
@@ -83,36 +88,35 @@ def init_events(bot, cli_flags):
|
||||
red_pkg = pkg_resources.get_distribution("Red-DiscordBot")
|
||||
dpy_version = discord.__version__
|
||||
|
||||
INFO = [
|
||||
str(bot.user),
|
||||
"Prefixes: {}".format(", ".join(prefixes)),
|
||||
"Language: {}".format(lang),
|
||||
"Red Bot Version: {}".format(red_version),
|
||||
"Discord.py Version: {}".format(dpy_version),
|
||||
"Shards: {}".format(bot.shard_count),
|
||||
"Storage type: {}".format(data_manager.storage_type()),
|
||||
]
|
||||
table_general_info = Table(show_edge=False, show_header=False)
|
||||
table_general_info.add_row("Prefixes", ", ".join(prefixes))
|
||||
table_general_info.add_row("Language", lang)
|
||||
table_general_info.add_row("Red version", red_version)
|
||||
table_general_info.add_row("Discord.py version", dpy_version)
|
||||
table_general_info.add_row("Storage type", data_manager.storage_type())
|
||||
|
||||
if guilds:
|
||||
INFO.extend(("Servers: {}".format(guilds), "Users: {}".format(users)))
|
||||
else:
|
||||
print("Ready. I'm not in any server yet!")
|
||||
|
||||
INFO.append("{} cogs with {} commands".format(len(bot.cogs), len(bot.commands)))
|
||||
table_counts = Table(show_edge=False, show_header=False)
|
||||
# String conversion is needed as Rich doesn't deal with ints
|
||||
table_counts.add_row("Shards", str(bot.shard_count))
|
||||
table_counts.add_row("Servers", str(guilds))
|
||||
if bot.intents.members: # Lets avoid 0 Unique Users
|
||||
table_counts.add_row("Unique Users", str(users))
|
||||
|
||||
outdated_red_message = ""
|
||||
rich_outdated_message = ""
|
||||
with contextlib.suppress(aiohttp.ClientError, asyncio.TimeoutError):
|
||||
pypi_version, py_version_req = await fetch_latest_red_version_info()
|
||||
outdated = pypi_version and pypi_version > red_version_info
|
||||
if outdated:
|
||||
INFO.append(
|
||||
"Outdated version! {} is available "
|
||||
"but you're using {}".format(pypi_version, red_version)
|
||||
)
|
||||
outdated_red_message = _(
|
||||
"Your Red instance is out of date! {} is the current "
|
||||
"version, however you are using {}!"
|
||||
).format(pypi_version, red_version)
|
||||
rich_outdated_message = (
|
||||
f"[red]Outdated version![/red]\n"
|
||||
f"[red]!!![/red]Version {pypi_version} is available, "
|
||||
f"but you're using {red_version}[red]!!![/red]"
|
||||
)
|
||||
current_python = platform.python_version()
|
||||
extra_update = _(
|
||||
"\n\nWhile the following command should work in most scenarios as it is "
|
||||
@@ -163,41 +167,33 @@ def init_events(bot, cli_flags):
|
||||
).format(py_version=current_python, req_py=py_version_req)
|
||||
outdated_red_message += extra_update
|
||||
|
||||
INFO2 = []
|
||||
bot._rich_console.print(INTRO)
|
||||
if guilds:
|
||||
bot._rich_console.print(
|
||||
Columns(
|
||||
[Panel(table_general_info, title=str(bot.user.name)), Panel(table_counts)],
|
||||
equal=True,
|
||||
align="center",
|
||||
)
|
||||
)
|
||||
else:
|
||||
bot._rich_console.print(Columns([Panel(table_general_info, title=str(bot.user.name))]))
|
||||
|
||||
reqs_installed = {"docs": None, "test": None}
|
||||
for key in reqs_installed.keys():
|
||||
reqs = [x.name for x in red_pkg._dep_map[key]]
|
||||
try:
|
||||
pkg_resources.require(reqs)
|
||||
except DistributionNotFound:
|
||||
reqs_installed[key] = False
|
||||
else:
|
||||
reqs_installed[key] = True
|
||||
|
||||
options = (
|
||||
("Voice", True),
|
||||
("Docs", reqs_installed["docs"]),
|
||||
("Tests", reqs_installed["test"]),
|
||||
bot._rich_console.print(
|
||||
"Loaded {} cogs with {} commands".format(len(bot.cogs), len(bot.commands))
|
||||
)
|
||||
|
||||
on_symbol, off_symbol, ascii_border = _get_startup_screen_specs()
|
||||
|
||||
for option, enabled in options:
|
||||
enabled = on_symbol if enabled else off_symbol
|
||||
INFO2.append("{} {}".format(enabled, option))
|
||||
|
||||
print(Fore.RED + INTRO)
|
||||
print(Style.RESET_ALL)
|
||||
print(bordered(INFO, INFO2, ascii_border=ascii_border))
|
||||
|
||||
if invite_url:
|
||||
print("\nInvite URL: {}\n".format(invite_url))
|
||||
|
||||
if not guilds:
|
||||
print(
|
||||
"Looking for a quick guide on setting up Red? https://docs.discord.red/en/stable/getting_started.html\n"
|
||||
bot._rich_console.print(
|
||||
f"\nInvite URL: {Text(invite_url, style=f'link {invite_url}')}"
|
||||
)
|
||||
# We generally shouldn't care if the client supports it or not as Rich deals with it.
|
||||
if not guilds:
|
||||
bot._rich_console.print(
|
||||
f"Looking for a quick guide on setting up Red? Checkout {Text('https://start.discord.red', style='link https://start.discord.red}')}"
|
||||
)
|
||||
if rich_outdated_message:
|
||||
bot._rich_console.print(rich_outdated_message)
|
||||
|
||||
if not bot.owner_ids:
|
||||
# we could possibly exit here in future
|
||||
|
||||
Reference in New Issue
Block a user