Skip to content

Commit

Permalink
Added the logger (1/3)
Browse files Browse the repository at this point in the history
  • Loading branch information
Debianov committed Jul 12, 2024
1 parent 2ed088b commit 8b3b3a3
Show file tree
Hide file tree
Showing 8 changed files with 49 additions and 12 deletions.
5 changes: 5 additions & 0 deletions bot/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@
from .main import BotConstructor
from .utils import ContextProvider, removeNesting

import logging.handlers

logging = logging.getLogger(__name__)

class UserLog(commands.Cog):

Expand Down Expand Up @@ -60,6 +63,8 @@ async def _on_command_error(
"указали корректные данные."
f" Необработанная часть сообщения: {ctx.current_argument}")
else:
logging.error(f"Unhadle exception {error}",
extra={"module_func": "commands -> _on_command_error"})
raise error

@commands.group(aliases=["logs"], invoke_without_command=True)
Expand Down
10 changes: 5 additions & 5 deletions bot/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,11 +159,11 @@ def __setattr__(
async def writeData(self) -> None:
async with self.dbconn.cursor() as acur:
await acur.execute("""
INSERT INTO target(context_id, target, act, d_in, name,
priority, output, other)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s);""",
[self.context_id, self.target, self.act, self.d_in,
self.name, self.priority, self.output, self.other])
INSERT INTO target(context_id, target, act, d_in, name,
priority, output, other)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s);""",
[self.context_id, self.target, self.act, self.d_in,
self.name, self.priority, self.output, self.other])

async def extractData(
self,
Expand Down
Empty file added bot/log-config.json
Empty file.
35 changes: 31 additions & 4 deletions bot/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
"""

import asyncio
import logging
import logging.handlers
import os
from typing import Any, Dict, Optional, Union

Expand All @@ -17,6 +19,24 @@
from .utils import ContextProvider, getEnvIfExist


def _init_logging() -> None:
logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
logging.getLogger('discord.http').setLevel(logging.INFO)

handler = logging.handlers.RotatingFileHandler(
filename='vtc-bot.log',
encoding='utf-8',
maxBytes=32 * 1024 * 1024, # 32 MiB
backupCount=5, # Rotate through 5 files
)
dt_fmt = '%Y-%m-%d %H:%M:%S'
formatter = logging.Formatter(
'[{asctime}] [{levelname:<8}] {module_func}: {message}',
dt_fmt, style='{')
handler.setFormatter(formatter)
logger.addHandler(handler)

class DBConnector:
"""
The main class for connecting to a PostgresSQL database.
Expand Down Expand Up @@ -47,6 +67,7 @@ async def initConnection(self) -> None:
def getDBconn(self) -> psycopg.AsyncConnection[Any]:
return self.dbconn


class BotConstructor(commands.Bot):
"""
The class for constructing the bot instance.
Expand Down Expand Up @@ -106,9 +127,10 @@ class DiscordObjectsLoader(psycopg.adapt.Loader):
def load(
self,
data: bytes
) -> Union[discord.abc.Messageable, discord.abc.Connectable, str]:
) -> Union[
discord.abc.Messageable, discord.abc.Connectable, str]:
string_data: str = data.decode()
ctx = context_provider.getContext() # type: ignore [union-attr]
ctx = context_provider.getContext() # type: ignore [union-attr]
for attr in ('get_member', 'get_user', 'get_channel'):
try:
result: Optional[discord.abc.Messageable] = getattr(
Expand All @@ -119,7 +141,7 @@ def load(
continue
return string_data

self.dbconn.adapters.register_dumper( # type: ignore [union-attr]
self.dbconn.adapters.register_dumper( # type: ignore [union-attr]
discord.abc.Messageable, DiscordObjectsDumper)
self.dbconn.adapters.register_loader("bigint[]", # type: ignore [union-attr]
DiscordObjectsLoader)
Expand All @@ -128,6 +150,7 @@ async def _initCogs(self) -> None:
for module_name in ("commands",):
await self.load_extension(f"bot.{module_name}")


async def DBConnFactory(**kwargs: str) -> psycopg.AsyncConnection[Any]:
"""
The factory for creating a done connection to the PostgresSQL database.
Expand All @@ -139,15 +162,18 @@ async def DBConnFactory(**kwargs: str) -> psycopg.AsyncConnection[Any]:
await dbconn_instance.initConnection()
return dbconn_instance.getDBconn()


def runForPoetry() -> None:
_init_logging()
loop = asyncio.get_event_loop()
if extract_envs := getEnvIfExist("POSTGRES_DBNAME", "POSTGRES_USER"):
dbconn = loop.run_until_complete(DBConnFactory(
dbname=extract_envs[0],
user=extract_envs[1]
))
else:
raise StartupBotError("Не удалось извлечь данные БД для подключения.")
raise StartupBotError(
"Не удалось извлечь данные БД для подключения.")
intents = discord.Intents.all()
intents.dm_messages = False
VCSBot = BotConstructor(
Expand All @@ -156,6 +182,7 @@ def runForPoetry() -> None:
command_prefix="sudo ",
intents=intents,
help_command=BotHelpCommand(),
log_handler=None
)
VCSBot.run(os.getenv("DISCORD_API_TOKEN"))

Expand Down
5 changes: 4 additions & 1 deletion bot/utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import builtins
import logging
import os
from typing import (
Any,
Expand All @@ -19,6 +20,7 @@

from bot.data import DiscordObjectsGroup

logger = logging.getLogger(__name__)

class ContextProvider:
"""
Expand Down Expand Up @@ -355,5 +357,6 @@ def getDiscordMemberID(obj: Any) -> Any:
if hasattr(obj, "id"):
return obj.id
else:
print("getDiscordMemberID", f"the id attr hasn't been found in {obj}. Skip.")
logger.info("getDiscordMemberID, the id attr hasn't been found in "
f"{obj}. Skip.")
return obj
1 change: 1 addition & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
sys.path.append(str(root))

from bot.utils import Case

# flake8: noqa: I005
pytest_plugins = ('pytest_asyncio',)

Expand Down
5 changes: 3 additions & 2 deletions tests/test_commands/test_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,8 +225,9 @@ async def test_log_1_good_expression(
)
for row in await acur.fetchall():
flags_values = [None, 0, None, None]
assert row == (row[0], str(mockLocator.guild.id), compared_objects["target"],
'23', compared_objects["d_in"], *flags_values)
assert row == (row[0], str(mockLocator.guild.id),
compared_objects["target"], '23', compared_objects["d_in"],
*flags_values)

@pytest.mark.parametrize(
"exp1, exp2, missing_params",
Expand Down
Empty file added vtc-bot.log
Empty file.

0 comments on commit 8b3b3a3

Please sign in to comment.