Improved logging

This commit is contained in:
Profitroll 2023-03-17 14:44:37 +01:00
parent 717586a9f0
commit 1f345e87f7
3 changed files with 61 additions and 10 deletions

View File

@ -65,7 +65,7 @@
}, },
"console": { "console": {
"shutdown": "Shutting down bot with pid {0}", "shutdown": "Shutting down bot with pid {0}",
"startup":"Starting with pid {0}", "startup": "Starting with pid {0}",
"keyboard_interrupt": "\nShutting down...", "keyboard_interrupt": "\nShutting down...",
"exception_occured": "Exception {0} happened on task execution", "exception_occured": "Exception {0} happened on task execution",
"post_sent": "Sent {0} to {1} with caption {2} and silently {3}", "post_sent": "Sent {0} to {1} with caption {2} and silently {3}",
@ -94,6 +94,12 @@
"cleanup_completed": "Performed cleanup of the sent files", "cleanup_completed": "Performed cleanup of the sent files",
"cleanup_unathorized": "Requested cleanup of sent files but not authorized. Please pass '--confirm' to perform that", "cleanup_unathorized": "Requested cleanup of sent files but not authorized. Please pass '--confirm' to perform that",
"cleanup_index_completed": "Performed cleanup of sent files index", "cleanup_index_completed": "Performed cleanup of sent files index",
"cleanup_index_unathorized": "Requested cleanup of sent files index but not authorized. Please pass '--confirm' to perform that" "cleanup_index_unathorized": "Requested cleanup of sent files index but not authorized. Please pass '--confirm' to perform that",
"random_pic_response": "Random pic response: {0}",
"random_pic_error_code": "Could not get photos from album {0}: HTTP {1}",
"random_pic_error_debug": "Could not get photos from '{0}/albums/{1}/photos?q=&page_size={2}&caption=queue' using token '{3}': HTTP {4}",
"find_pic_error": "Could not find image with name '{0}' and caption '{1}' due to: {2}",
"pic_upload_error": "Could not upload '{0}' to API: HTTP {1} with message '{2}'",
"api_creds_invalid": "Incorrect API credentials! Could not login into '{0}' using login '{1}': HTTP {2}"
} }
} }

View File

@ -94,6 +94,12 @@
"cleanup_completed": "Виконано очищення надісланих файлів", "cleanup_completed": "Виконано очищення надісланих файлів",
"cleanup_unathorized": "Надіслано запит на очищення надісланих файлів, але не авторизовано. Для цього надайте аргумент '--confirm'", "cleanup_unathorized": "Надіслано запит на очищення надісланих файлів, але не авторизовано. Для цього надайте аргумент '--confirm'",
"cleanup_index_completed": "Виконано очищення індексу надісланих файлів", "cleanup_index_completed": "Виконано очищення індексу надісланих файлів",
"cleanup_index_unathorized": "Надіслано запит на очищення індексу надісланих файлів, але не авторизовано. Для цього надайте аргумент '--confirm'" "cleanup_index_unathorized": "Надіслано запит на очищення індексу надісланих файлів, але не авторизовано. Для цього надайте аргумент '--confirm'",
"random_pic_response": "Відповідь на пошук випадкової картинки: {0}",
"random_pic_error_code": "Не вдалося отримати фото з альбому {0}: HTTP {1}",
"random_pic_error_debug": "Не вдалося отримати фотографії з '{0}/albums/{1}/photos?q=&page_size={2}&caption=queue', використовуючи токен '{3}': HTTP {4}",
"find_pic_error": "Не вдалося знайти зображення з назвою '{0}' та підписом '{1}' через: {2}",
"pic_upload_error": "Не вдалося завантажити '{0}' до API: HTTP {1} з повідомленням '{2}'",
"api_creds_invalid": "Невірні облікові дані API! Не вдалося увійти в '{0}' за допомогою логіна '{1}': HTTP {2}"
} }
} }

View File

@ -20,7 +20,7 @@ from classes.exceptions import (
UserCreationError, UserCreationError,
) )
from modules.logger import logWrite from modules.logger import logWrite
from modules.utils import configGet from modules.utils import configGet, locale
http_session = ClientSession( http_session = ClientSession(
json_serialize=dumps, json_serialize=dumps,
@ -52,7 +52,15 @@ async def authorize() -> str:
) )
if not response.ok: if not response.ok:
logWrite( logWrite(
f'Incorrect API credentials! Could not login into "{configGet("address", "posting", "api")}" using login "{configGet("username", "posting", "api")}": HTTP {response.status}' locale(
"api_creds_invalid",
"console",
locale=configGet("locale_log").format(
configGet("address", "posting", "api"),
configGet("username", "posting", "api"),
response.status,
),
)
) )
raise ValueError raise ValueError
async with aiofiles.open( async with aiofiles.open(
@ -78,13 +86,34 @@ async def random_pic(token: Union[str, None] = None) -> Tuple[str, str]:
f'{configGet("address", "posting", "api")}/albums/{configGet("album", "posting", "api")}/photos?q=&page_size={configGet("page_size", "posting")}&caption=queue', f'{configGet("address", "posting", "api")}/albums/{configGet("album", "posting", "api")}/photos?q=&page_size={configGet("page_size", "posting")}&caption=queue',
headers={"Authorization": f"Bearer {token}"}, headers={"Authorization": f"Bearer {token}"},
) )
logWrite("Random pic response: " + str(await resp.json()), debug=True) logWrite(
locale("random_pic_response", "console", locale=configGet("locale_log")).format(
await resp.json()
),
debug=True,
)
if resp.status != 200: if resp.status != 200:
logWrite( logWrite(
f'Could not get photos from album {configGet("album", "posting", "api")}: HTTP {resp.status}' locale(
"random_pic_error_code",
"console",
locale=configGet("locale_log").format(
configGet("album", "posting", "api"), resp.status
),
),
) )
logWrite( logWrite(
f'Could not get photos from "{configGet("address", "posting", "api")}/albums/{configGet("album", "posting", "api")}/photos?q=&page_size={configGet("page_size", "posting")}&caption=queue" using token "{token}": HTTP {resp.status}', locale(
"random_pic_error_debug",
"console",
locale=configGet("locale_log").format(
configGet("address", "posting", "api"),
configGet("album", "posting", "api"),
configGet("page_size", "posting"),
token,
resp.status,
),
),
debug=True, debug=True,
) )
raise ValueError raise ValueError
@ -120,7 +149,13 @@ async def upload_pic(
response_json = await response.json() response_json = await response.json()
if response.status != 200 and response.status != 409: if response.status != 200 and response.status != 409:
logWrite( logWrite(
f"Could not upload '{filepath}' to API: HTTP {response.status} with message '{response.content}'" locale(
"pic_upload_error",
"console",
locale=configGet("locale_log").format(
filepath, response.status, response.content
),
),
) )
raise SubmissionUploadError( raise SubmissionUploadError(
str(filepath), response.status, response.content str(filepath), response.status, response.content
@ -161,7 +196,11 @@ async def find_pic(
return (await response.json())["results"] return (await response.json())["results"]
except Exception as exp: except Exception as exp:
logWrite( logWrite(
f"Could not find image with name '{name}' and caption '{caption}' due to: {exp}" locale(
"find_pic_error",
"console",
locale=configGet("locale_log").format(name, caption, exp),
),
) )
return None return None