basic logging

This commit is contained in:
kiriharu 2021-01-05 20:43:18 +03:00
parent b755a24ce2
commit 41cec1f044
5 changed files with 27 additions and 4 deletions

View File

@ -1,6 +1,6 @@
from aiogram import Bot, Dispatcher, executor from aiogram import Bot, Dispatcher, executor
from aiogram.contrib.fsm_storage.memory import MemoryStorage from aiogram.contrib.fsm_storage.memory import MemoryStorage
from tgbot.middlewares import WriteCommandMetric from tgbot.middlewares import WriteCommandMetric, LoggingMiddleware
import config import config
import handlers import handlers
@ -12,6 +12,7 @@ dp = Dispatcher(telegram_bot, storage=storage)
def on_startup(): def on_startup():
handlers.default.setup(dp) handlers.default.setup(dp)
dp.middleware.setup(WriteCommandMetric()) dp.middleware.setup(WriteCommandMetric())
dp.middleware.setup(LoggingMiddleware())
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -7,7 +7,8 @@ from aiogram.bot import Bot
from datetime import datetime from datetime import datetime
from core.coretypes import APINodeInfo from core.coretypes import APINodeInfo
from .helpers import send_api_requests, check_int, validate_local from .helpers import send_api_requests, check_int, validate_local
from .metrics import push_metric from loguru import logger
from uuid import uuid4
header = "Отчет о проверке хоста:" \ header = "Отчет о проверке хоста:" \
"\n\n— Хост: {target_fq}"\ "\n\n— Хост: {target_fq}"\
@ -45,12 +46,15 @@ class CheckerBaseHandler:
try: try:
args = await self.process_args(message.text) args = await self.process_args(message.text)
except NotEnoughArgs: except NotEnoughArgs:
logger.info(f"User {message.from_user.id} got NotEnoughArgs error")
return await message.answer(self.help_message, parse_mode="Markdown") return await message.answer(self.help_message, parse_mode="Markdown")
except InvalidPort: except InvalidPort:
logger.info(f"User {message.from_user.id} got InvalidPort error")
return await message.answer(self.invalid_port_message, parse_mode="Markdown") return await message.answer(self.invalid_port_message, parse_mode="Markdown")
try: try:
await self.validate_target(args[0]) await self.validate_target(args[0])
except LocalhostForbidden: except LocalhostForbidden:
logger.info(f"User {message.from_user.id} got LocalhostForbidden error")
return await message.answer(self.localhost_forbidden_message, parse_mode="Markdown") return await message.answer(self.localhost_forbidden_message, parse_mode="Markdown")
await self.check( await self.check(
message.chat.id, message.chat.id,
@ -59,6 +63,9 @@ class CheckerBaseHandler:
) )
async def check(self, chat_id: int, bot: Bot, data: dict): async def check(self, chat_id: int, bot: Bot, data: dict):
# TODO: start check and end check metrics with ident, chat_id and api_endpoint
ident = uuid4().hex
logger.info(f"User {chat_id} started check {ident}")
rsp_msg = await bot.send_message(chat_id, header.format(**data)) rsp_msg = await bot.send_message(chat_id, header.format(**data))
iter_keys = 1 # because I can't use enumerate iter_keys = 1 # because I can't use enumerate
# using generators for magic... # using generators for magic...
@ -70,6 +77,7 @@ class CheckerBaseHandler:
node_formatted_response = await self.prepare_message(res) node_formatted_response = await self.prepare_message(res)
rsp_msg = await rsp_msg.edit_text(rsp_msg.text + f"\n\n{iter_keys}. {node_formatted_response}") rsp_msg = await rsp_msg.edit_text(rsp_msg.text + f"\n\n{iter_keys}. {node_formatted_response}")
iter_keys = iter_keys + 1 iter_keys = iter_keys + 1
logger.info(f"User {chat_id} ended check {ident}")
await rsp_msg.edit_text(rsp_msg.text + f"\n\nПроверка завершена❗") await rsp_msg.edit_text(rsp_msg.text + f"\n\nПроверка завершена❗")
async def validate_target(self, target: str): async def validate_target(self, target: str):

View File

@ -3,7 +3,7 @@ from typing import List
from core.coretypes import APINode from core.coretypes import APINode
from ipaddress import ip_address from ipaddress import ip_address
from contextlib import suppress from contextlib import suppress
from loguru import logger
from tgbot.handlers.metrics import push_api_request_status from tgbot.handlers.metrics import push_api_request_status
@ -45,7 +45,8 @@ async def send_api_requests(endpoint: str, data: dict, nodes: List[APINode]):
result = await client.get( result = await client.get(
f"{node.address}/{endpoint}", params=data f"{node.address}/{endpoint}", params=data
) )
except ConnectError: except ConnectError as e:
logger.error(f"Node {node.address} got ConnectionError. Full exception: {e}")
# TODO: Report problems to admins # TODO: Report problems to admins
# We yield 500 response when backend is offline # We yield 500 response when backend is offline
result = Response(500) result = Response(500)

View File

@ -1 +1,2 @@
from tgbot.middlewares.write_command_metric import WriteCommandMetric from tgbot.middlewares.write_command_metric import WriteCommandMetric
from tgbot.middlewares.logging import LoggingMiddleware

View File

@ -0,0 +1,12 @@
from aiogram.dispatcher.middlewares import BaseMiddleware
from aiogram.types import Message
from loguru import logger
class LoggingMiddleware(BaseMiddleware):
def __init__(self):
super().__init__()
async def on_process_message(self, message: Message, data: dict):
logger.info(f"User {message.from_user.id} issued command: {message.text}")