Updated logging system

This commit is contained in:
Choco
2024-03-18 20:45:31 +08:00
parent 4655b6e54c
commit e68788f429
7 changed files with 39 additions and 48 deletions

View File

@@ -85,7 +85,7 @@ class A_ZLyrics(LyricsPlatform):
lyrics = max(divs, key=len).strip()
if not lyrics:
return print("Lyrics not found")
return None
lyrics_parts = re.split(r"(\[[\w\S_ ]+\:])", lyrics)
lyrics_parts = [item for item in lyrics_parts if item != ""]

View File

@@ -46,10 +46,11 @@ class Listeners(commands.Cog):
bot=self.bot,
spotify_client_id=func.tokens.spotify_client_id,
spotify_client_secret=func.tokens.spotify_client_secret,
logger=func.logger,
**n
)
except Exception as e:
print(f'Node {n["identifier"]} is not able to connect! - Reason: {e}')
func.logger.error(f'Node {n["identifier"]} is not able to connect! - Reason: {e}')
@commands.Cog.listener()
async def on_voicelink_track_end(self, player: voicelink.Player, track, _):

View File

@@ -120,7 +120,7 @@ class Task(commands.Cog):
try:
await report_channel.send(content=f"Report Before: <t:{round(datetime.timestamp(datetime.now()))}:F>", file=errorFile)
except Exception as e:
print(f"Report could not be sent (Reason: {e})")
func.logger.error(f"Report could not be sent (Reason: {e})")
func.ERROR_LOGS.clear()
async def setup(bot: commands.Bot):

View File

@@ -1,4 +1,4 @@
import discord, json, os, copy
import discord, json, os, copy, logging
from discord.ext import commands
from datetime import datetime
@@ -20,6 +20,7 @@ if not os.path.exists(os.path.join(ROOT_DIR, "settings.json")):
#--------------- Cache Var ---------------
tokens: TOKENS = TOKENS()
settings: Settings
logger: logging.Logger = logging.getLogger("vocard")
MONGO_DB: AsyncIOMotorClient
SETTINGS_DB: AsyncIOMotorCollection

26
main.py
View File

@@ -4,6 +4,7 @@ import os
import traceback
import aiohttp
import update
import logging
import function as func
from discord.ext import commands
@@ -15,10 +16,10 @@ from addons import Settings
class Translator(discord.app_commands.Translator):
async def load(self):
print("Loaded Translator")
func.logger.info("Loaded Translator")
async def unload(self):
print("Unload Translator")
func.logger.info("Unload Translator")
async def translate(self, string: discord.app_commands.locale_str, locale: discord.Locale, context: discord.app_commands.TranslationContext):
if str(locale) in func.LOCAL_LANGS:
@@ -55,7 +56,7 @@ class Vocard(commands.Bot):
try:
func.MONGO_DB = AsyncIOMotorClient(host=db_url)
await func.MONGO_DB.server_info()
print("Successfully connected to MongoDB!")
func.logger.info(f"Successfully connected to [{db_name}] MongoDB!")
except Exception as e:
raise Exception("Not able to connect MongoDB! Reason:", e)
@@ -74,9 +75,9 @@ class Vocard(commands.Bot):
if module.endswith('.py'):
try:
await self.load_extension(f"cogs.{module[:-3]}")
print(f"Loaded {module[:-3]}")
func.logger.info(f"Loaded {module[:-3]}")
except Exception as e:
print(traceback.format_exc())
func.logger.error(f"Something went wrong while loading {module[:-3]} cog.", traceback.format_exc())
if func.settings.ipc_server.get("enable", False):
await self.ipc.start()
@@ -88,13 +89,13 @@ class Vocard(commands.Bot):
await self.tree.sync()
async def on_ready(self):
print("------------------")
print(f"Logging As {self.user}")
print(f"Bot ID: {self.user.id}")
print("------------------")
print(f"Discord Version: {discord.__version__}")
print(f"Python Version: {sys.version}")
print("------------------")
func.logger.info("------------------")
func.logger.info(f"Logging As {self.user}")
func.logger.info(f"Bot ID: {self.user.id}")
func.logger.info("------------------")
func.logger.info(f"Discord Version: {discord.__version__}")
func.logger.info(f"Python Version: {sys.version}")
func.logger.info("------------------")
func.tokens.client_id = self.user.id
func.LOCAL_LANGS.clear()
@@ -147,6 +148,7 @@ async def get_prefix(bot, message: discord.Message):
# Loading settings
func.settings = Settings(func.open_json("settings.json"))
func.logger.setLevel(getattr(logging, func.settings.logging_level.upper(), None))
# Setup the bot object
intents = discord.Intents.default()

View File

@@ -76,7 +76,8 @@ async def connect_channel(ctx: Union[commands.Context, Interaction], channel: Vo
channel, ctx, settings
))
await player.send_ws({"op": "createPlayer", "members_id": [member.id for member in channel.members]})
# if player.client.ipc._is_connected:
# await player.send_ws({"op": "createPlayer", "members_id": [member.id for member in channel.members]})
return player
@@ -140,7 +141,7 @@ class Player(VoiceProtocol):
self.stop_votes = set()
self._ph = Placeholders(client, self)
self._logger: logging.Logger = self._node.logger
self._logger: Optional[logging.Logger] = self._node._logger
def __repr__(self):
return (
@@ -265,7 +266,7 @@ class Player(VoiceProtocol):
self._is_connected = state.get("connected")
self._last_position = state.get("position")
self._ping = state.get("ping")
self._logger.debug(f"Player update state with data {data}")
self._logger.debug(f"Player in {self.guild.name}({self.guild.id}) update state with data {data}")
if self.is_ipc_connected:
await self.send_ws({
@@ -292,7 +293,7 @@ class Player(VoiceProtocol):
data = {"voice": data}
)
self._logger.debug(f"Dispatched voice update to {state['event']['endpoint']} with data {data}")
self._logger.debug(f"Player in {self.guild.name}({self.guild.id}) dispatched voice update to {state['event']['endpoint']} with data {data}")
async def on_voice_server_update(self, data: dict):
self._voice_state.update({"event": data})
@@ -325,7 +326,7 @@ class Player(VoiceProtocol):
if isinstance(event, TrackStartEvent):
self._ending_track = self._current
self._logger.debug(f"Dispatched event {event_type} to player.")
self._logger.debug(f"Player in {self.guild.name}({self.guild.id}) dispatched event {event_type}.")
async def do_next(self):
if self.is_playing or not self.channel:
@@ -357,7 +358,7 @@ class Player(VoiceProtocol):
try:
await self.play(track, start=track.position)
except Exception as e:
print(f"Something went wrong while playing music in {self.guild.name}({self.guild.id})", e)
self._logger.error(f"Something went wrong while playing music in {self.guild.name}({self.guild.id})", e)
await sleep(5)
return await self.do_next()
@@ -368,7 +369,7 @@ class Player(VoiceProtocol):
if self.settings.get('controller', True):
await self.invoke_controller()
if self.is_ipc_connected:
await self.send_ws({
"op": "trackUpdate",
@@ -396,7 +397,7 @@ class Player(VoiceProtocol):
await self.controller.edit(embed=embed, view=view)
except Exception as e:
print(f"Something went wrong while sending music controller to {self.guild.name}({self.guild.id})", e)
self._logger.error(f"Something went wrong while sending music controller to {self.guild.name}({self.guild.id})", e)
pass
self.updating = False
@@ -536,7 +537,7 @@ class Player(VoiceProtocol):
if self.volume != 100:
await self.set_volume(self.volume)
self._logger.debug(f"Playing {track.title} from uri {track.uri} with a length of {track.length}")
self._logger.debug(f"Player in {self.guild.name}({self.guild.id}) playing {track.title} from uri {track.uri} with a length of {track.length}")
return self._current
async def add_track(self, raw_tracks: Union[Track, List[Track]], *, at_font: bool = False, duplicate: bool = True) -> int:

View File

@@ -28,7 +28,6 @@ import os
import re
import aiohttp
import logging
import function as func
from discord import Client, Member
from discord.ext.commands import Bot
@@ -87,13 +86,13 @@ class Node:
port: int,
password: str,
identifier: str,
logger: logging.Logger,
secure: bool = False,
heartbeat: int = 30,
session: Optional[aiohttp.ClientSession] = None,
spotify_client_id: Optional[str] = None,
spotify_client_secret: Optional[str] = None,
resume_key: Optional[str] = None,
logger: Optional[logging.Logger] = None
):
self._bot: Bot = bot
self._host: str = host
@@ -101,9 +100,9 @@ class Node:
self._pool: NodePool = pool
self._password: str = password
self._identifier: str = identifier
self.logger: logging.Logger = logger
self._heartbeat: int = heartbeat
self._secure: bool = secure
self._logger: Optional[logging.Logger] = logger
self._websocket_uri: str = f"{'wss' if self._secure else 'ws'}://{self._host}:{self._port}/" + NODE_VERSION + "/websocket"
self._rest_uri: str = f"{'https' if self._secure else 'http'}://{self._host}:{self._port}"
@@ -124,7 +123,7 @@ class Node:
}
self._players: Dict[int, Player] = {}
self._spotify_client_id: Optional[str] = spotify_client_id
self._spotify_client_secret: Optional[str] = spotify_client_secret
self._spotify_client: Optional[spotify.Client] = None
@@ -222,7 +221,7 @@ class Node:
self._available = False
retry = backoff.delay()
self.logger.info(f"Trying to reconnect node [{self._identifier}] with {round(retry)}s")
self._logger.info(f"Trying to reconnect node [{self._identifier}] with {round(retry)}s")
await asyncio.sleep(retry)
if not self.is_connected:
try:
@@ -296,7 +295,7 @@ class Node:
self._task = self._bot.loop.create_task(self._listen())
self._available = True
self.logger.info(f"Node [{self._identifier}] is connected!")
self._logger.info(f"Node [{self._identifier}] is connected!")
except aiohttp.ClientConnectorError:
raise NodeConnectionFailure(
@@ -543,17 +542,6 @@ class NodePool:
def node_count(self) -> Optional[Node]:
return len(self._nodes.values())
@classmethod
def _setup_logging(cls, level_name: str = "INFO") -> logging.Logger:
logger = logging.getLogger("voicelink")
level = getattr(logging, level_name.upper(), None)
if not isinstance(level, int):
raise ValueError(f'Invalid log level: {level_name}')
logger.setLevel(level)
return logger
@classmethod
def get_best_node(cls, *, algorithm: NodeAlgorithm) -> Node:
"""Fetches the best node based on an NodeAlgorithm.
@@ -615,7 +603,8 @@ class NodePool:
spotify_client_id: Optional[str] = None,
spotify_client_secret: Optional[str] = None,
session: Optional[aiohttp.ClientSession] = None,
resume_key: Optional[str] = None
resume_key: Optional[str] = None,
logger: Optional[logging.Logger] = None
) -> Node:
"""Creates a Node object to be then added into the node pool.
For Spotify searching capabilites, pass in valid Spotify API credentials.
@@ -623,14 +612,11 @@ class NodePool:
if identifier in cls._nodes.keys():
raise NodeCreationError(f"A node with identifier '{identifier}' already exists.")
if not cls._logger:
cls._logger = cls._setup_logging(func.settings.logging_level)
node = Node(
pool=cls, bot=bot, host=host, port=port, password=password,
identifier=identifier, logger=cls._logger,secure=secure, heartbeat=heartbeat, spotify_client_id=spotify_client_id,
identifier=identifier, secure=secure, heartbeat=heartbeat, spotify_client_id=spotify_client_id,
session=session, spotify_client_secret=spotify_client_secret,
resume_key=resume_key
resume_key=resume_key, logger=logger
)
await node.connect()