feat(logging): migrate VK API jobs and services to vk channel

This commit is contained in:
F4ilji
2026-07-05 23:26:41 +05:00
parent 720aa4d0ae
commit 41b00fcdae
9 changed files with 53 additions and 54 deletions
+1 -1
View File
@@ -50,7 +50,7 @@ class CreateVkPost implements ShouldQueue
); );
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Ошибка при создании поста: ' . $e->getMessage()); Log::channel('vk')->error('Failed to create VK post', ['error' => $e->getMessage()]);
throw $e; // Перебрасываем исключение для повторной попытки throw $e; // Перебрасываем исключение для повторной попытки
} }
} }
+29 -27
View File
@@ -46,8 +46,7 @@ class CreateVkPostJob implements ShouldQueue
public function handle() public function handle()
{ {
$logPrefix = "[VK Job {$this->post_id}]"; Log::channel('vk')->info('Processing VK post', ['post_id' => $this->post_id, 'images' => count($this->images)]);
Log::info("{$logPrefix} Начало обработки поста. Входящие изображения: " . count($this->images));
$vk = new VKApiClient(); $vk = new VKApiClient();
$wallService = new VkWallService($vk); $wallService = new VkWallService($vk);
@@ -64,44 +63,48 @@ class CreateVkPostJob implements ShouldQueue
$attached_videos = array_slice($video_list, 0, count($video_list)); $attached_videos = array_slice($video_list, 0, count($video_list));
$remaining_slots = $available_slots; $remaining_slots = $available_slots;
Log::info("{$logPrefix} Видео: " . count($attached_videos) . ", Осталось слотов для фото: {$remaining_slots}"); Log::channel('vk')->debug('Attachment slots calculated', [
'post_id' => $this->post_id,
'videos' => count($attached_videos),
'remaining_photo_slots' => $remaining_slots,
]);
$image_list = []; $image_list = [];
if ($remaining_slots > 0 && !empty($this->images)) { if ($remaining_slots > 0 && !empty($this->images)) {
$images_to_attach = array_slice($this->images, 0, $remaining_slots); $images_to_attach = array_slice($this->images, 0, $remaining_slots);
Log::info("{$logPrefix} Начинаем подготовку фото для стены", ['files' => $images_to_attach]); Log::channel('vk')->debug('Preparing wall photos', ['files' => $images_to_attach]);
$image_attachments = $this->prepareWallPhotos($images_to_attach); $image_attachments = $this->prepareWallPhotos($images_to_attach);
Log::info("{$logPrefix} Результат подготовки фото (строка): '{$image_attachments}'"); Log::channel('vk')->debug('Photo preparation result', ['attachments' => $image_attachments]);
$image_list = $image_attachments ? explode(',', $image_attachments) : []; $image_list = $image_attachments ? explode(',', $image_attachments) : [];
} else { } else {
Log::info("{$logPrefix} Фото не будут добавлены (нет слотов или нет фото)."); Log::channel('vk')->debug('No photos to attach — no slots or no images', ['post_id' => $this->post_id]);
} }
$selected_attachments = array_merge($attached_videos, $image_list); $selected_attachments = array_merge($attached_videos, $image_list);
if (count($this->images) > count($image_list)) { if (count($this->images) > count($image_list)) {
Log::info("{$logPrefix} Не все фото вошли в пост. Создаем альбом."); Log::channel('vk')->debug('Not all photos fit in post — creating album', ['post_id' => $this->post_id]);
$album = $this->createAlbum($this->title, $this->images); $album = $this->createAlbum($this->title, $this->images);
if (isset($album['id'])) { if (isset($album['id'])) {
$albumLink = "https://vk.ru/album-{$this->public_id}_{$album['id']}"; $albumLink = "https://vk.ru/album-{$this->public_id}_{$album['id']}";
$this->message .= "\n\n[{$albumLink}|Ссылка на все фотографии]"; $this->message .= "\n\n[{$albumLink}|Ссылка на все фотографии]";
} else { } else {
Log::error("{$logPrefix} Не удалось создать альбом"); Log::channel('vk')->error('Failed to create VK album', ['post_id' => $this->post_id]);
} }
} }
$attachmentString = implode(',', $selected_attachments); $attachmentString = implode(',', $selected_attachments);
Log::info("{$logPrefix} Финальная строка вложений: '{$attachmentString}'"); Log::channel('vk')->debug('Final attachment string', ['post_id' => $this->post_id, 'attachments' => $attachmentString]);
$vk_post = $wallService->createPost($this->message, $from_group, $attachmentString, $this->publish_date, $this->primary_attachments_mode); $vk_post = $wallService->createPost($this->message, $from_group, $attachmentString, $this->publish_date, $this->primary_attachments_mode);
if (isset($vk_post['post_id'])) { if (isset($vk_post['post_id'])) {
Log::info("{$logPrefix} Пост успешно создан ID: {$vk_post['post_id']}"); Log::channel('vk')->info('VK post created successfully', ['post_id' => $this->post_id, 'vk_post_id' => $vk_post['post_id']]);
DB::table('posts_vk_posts')->insert( DB::table('posts_vk_posts')->insert(
[ [
'post_id' => $this->post_id, 'post_id' => $this->post_id,
@@ -110,7 +113,7 @@ class CreateVkPostJob implements ShouldQueue
] ]
); );
} else { } else {
Log::error("{$logPrefix} Ошибка создания поста в VK", ['response' => $vk_post]); Log::channel('vk')->error('Failed to create VK post', ['post_id' => $this->post_id, 'response' => $vk_post]);
} }
} }
@@ -131,16 +134,16 @@ class CreateVkPostJob implements ShouldQueue
if (file_exists($fullPath)) { if (file_exists($fullPath)) {
$imagePaths[] = $fullPath; $imagePaths[] = $fullPath;
} else { } else {
Log::warning("Файл не найден на диске: {$img} (Искали: {$fullPath})"); Log::channel('vk')->warning('Image file not found on disk', ['image' => $img, 'expected_path' => $fullPath]);
} }
} }
if (empty($imagePaths)) { if (empty($imagePaths)) {
Log::info("Нет валидных локальных путей для фото."); Log::channel('vk')->debug('No valid local image paths found', ['post_id' => $this->post_id]);
return ''; return '';
} }
Log::info("Локальные пути изображений для загрузки:", $imagePaths); Log::channel('vk')->debug('Local image paths for upload', ['paths' => $imagePaths]);
$photos = $this->uploadWallPhotos($imagePaths, $this->public_id); $photos = $this->uploadWallPhotos($imagePaths, $this->public_id);
@@ -151,7 +154,7 @@ class CreateVkPostJob implements ShouldQueue
return $result; return $result;
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error("Ошибка при подготовке фотографий: " . $e->getMessage()); Log::channel('vk')->error('Failed to prepare wall photos', ['error' => $e->getMessage()]);
return ''; return '';
} }
} }
@@ -162,14 +165,14 @@ class CreateVkPostJob implements ShouldQueue
foreach ($imagePaths as $imagePath) { foreach ($imagePaths as $imagePath) {
try { try {
Log::info("--- Загрузка фото: {$imagePath} ---"); Log::channel('vk')->debug('Uploading photo', ['path' => $imagePath]);
// 1. Проверка доступности файла // 1. Проверка доступности файла
$fileContent = @file_get_contents($imagePath); $fileContent = @file_get_contents($imagePath);
if ($fileContent === false) { if ($fileContent === false) {
throw new \Exception("Не удалось прочитать файл по ссылке: {$imagePath}. Проверьте доступность URL."); throw new \Exception("Не удалось прочитать файл по ссылке: {$imagePath}. Проверьте доступность URL.");
} }
Log::info("Файл прочитан, размер: " . strlen($fileContent) . " байт."); Log::channel('vk')->debug('File read successfully', ['path' => $imagePath, 'size_bytes' => strlen($fileContent)]);
// 2. Получение сервера // 2. Получение сервера
$uploadServerResponse = Http::get('https://api.vk.ru/method/photos.getWallUploadServer', [ $uploadServerResponse = Http::get('https://api.vk.ru/method/photos.getWallUploadServer', [
@@ -181,16 +184,16 @@ class CreateVkPostJob implements ShouldQueue
$uploadServerData = $uploadServerResponse->json(); $uploadServerData = $uploadServerResponse->json();
if (isset($uploadServerData['error'])) { if (isset($uploadServerData['error'])) {
Log::error("VK API Error getWallUploadServer: ", $uploadServerData['error']); Log::channel('vk')->error('VK API getWallUploadServer error', ['error' => $uploadServerData['error']]);
continue; continue;
} }
if (!isset($uploadServerData['response']['upload_url'])) { if (!isset($uploadServerData['response']['upload_url'])) {
Log::error("Ответ getWallUploadServer не содержит upload_url", $uploadServerData); Log::channel('vk')->error('getWallUploadServer response missing upload_url', ['response' => $uploadServerData]);
throw new \Exception('Не удалось получить сервер для загрузки: ' . $imagePath); throw new \Exception('Не удалось получить сервер для загрузки: ' . $imagePath);
} }
$uploadUrl = $uploadServerData['response']['upload_url']; $uploadUrl = $uploadServerData['response']['upload_url'];
Log::info("Upload URL получен: {$uploadUrl}"); Log::channel('vk')->debug('Upload URL obtained', ['url' => $uploadUrl]);
// 3. Отправка файла // 3. Отправка файла
$uploadResponse = Http::attach( $uploadResponse = Http::attach(
@@ -202,7 +205,7 @@ class CreateVkPostJob implements ShouldQueue
$uploadData = $uploadResponse->json(); $uploadData = $uploadResponse->json();
// Логируем сырой ответ от сервера загрузки, часто ошибка тут // Логируем сырой ответ от сервера загрузки, часто ошибка тут
Log::info("Результат POST загрузки:", $uploadData ?? []); Log::channel('vk')->debug('Upload POST response', ['response' => $uploadData ?? []]);
if (!isset($uploadData['photo']) || !isset($uploadData['server']) || !isset($uploadData['hash'])) { if (!isset($uploadData['photo']) || !isset($uploadData['server']) || !isset($uploadData['hash'])) {
// Иногда VK возвращает пустой photo: "[]" или error внутри JSON // Иногда VK возвращает пустой photo: "[]" или error внутри JSON
@@ -222,21 +225,20 @@ class CreateVkPostJob implements ShouldQueue
$saveData = $saveResponse->json(); $saveData = $saveResponse->json();
if (isset($saveData['error'])) { if (isset($saveData['error'])) {
Log::error("VK API Error photos.saveWallPhoto: ", $saveData['error']); Log::channel('vk')->error('VK API saveWallPhoto error', ['error' => $saveData['error']]);
continue; continue;
} }
if (!isset($saveData['response'][0])) { if (!isset($saveData['response'][0])) {
Log::error("Не удалось сохранить фото (нет response[0])", $saveData); Log::channel('vk')->error('saveWallPhoto missing response[0]', ['response' => $saveData]);
throw new \Exception('Не удалось сохранить фотографию: ' . $imagePath); throw new \Exception('Не удалось сохранить фотографию: ' . $imagePath);
} }
$uploadedPhotos[] = $saveData['response'][0]; $uploadedPhotos[] = $saveData['response'][0];
Log::info("Фотография успешно сохранена. ID: " . $saveData['response'][0]['id']); Log::channel('vk')->debug('Photo saved successfully', ['photo_id' => $saveData['response'][0]['id']]);
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error("Критическая ошибка при загрузке {$imagePath}: " . $e->getMessage()); Log::channel('vk')->error('Critical error uploading photo', ['path' => $imagePath, 'error' => $e->getMessage()]);
Log::error($e->getTraceAsString());
} }
} }
@@ -289,7 +291,7 @@ class CreateVkPostJob implements ShouldQueue
$attachment = "video{$uploadData['owner_id']}_{$uploadData['video_id']}"; $attachment = "video{$uploadData['owner_id']}_{$uploadData['video_id']}";
$uploadedVideos[] = $attachment; $uploadedVideos[] = $attachment;
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error("Ошибка при загрузке видео {$videoPath}: " . $e->getMessage()); Log::channel('vk')->error('Failed to upload video', ['path' => $videoPath, 'error' => $e->getMessage()]);
} }
} }
return $uploadedVideos; return $uploadedVideos;
+1 -1
View File
@@ -34,7 +34,7 @@ class UpdateVkPost implements ShouldQueue
$vkService = new VkService(); $vkService = new VkService();
$vkService->updatePost($postRelation->vk_post_id, $this->title, $this->text, $this->images, $this->publish_date); $vkService->updatePost($postRelation->vk_post_id, $this->title, $this->text, $this->images, $this->publish_date);
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Ошибка при создании поста: ' . $e->getMessage()); Log::channel('vk')->error('Failed to update VK post', ['error' => $e->getMessage()]);
throw $e; // Перебрасываем исключение для повторной попытки throw $e; // Перебрасываем исключение для повторной попытки
} }
} }
+7 -10
View File
@@ -55,13 +55,10 @@ class UpdateVkPostJob implements ShouldQueue
$vk_post = $wallService->getPostById($this->post_id); $vk_post = $wallService->getPostById($this->post_id);
// доделать
if ($vk_post['attachments']) { if ($vk_post['attachments']) {
Log::info($vk_post);
if ($this->getAlbumAttachment($vk_post['attachments'])) { if ($this->getAlbumAttachment($vk_post['attachments'])) {
Log::info('вход в аттачментс вк');
$album = $this->getAlbumAttachment($vk_post['attachments']); $album = $this->getAlbumAttachment($vk_post['attachments']);
Log::info($album); Log::channel('vk')->debug('Deleting existing album before update', ['album_id' => $album['album']['id']]);
$albumService->deleteAlbum($album['album']['id'], $this->public_id); $albumService->deleteAlbum($album['album']['id'], $this->public_id);
} }
} }
@@ -85,7 +82,7 @@ class UpdateVkPostJob implements ShouldQueue
$image_attachments = $this->prepareWallPhotos($images_to_attach); $image_attachments = $this->prepareWallPhotos($images_to_attach);
$image_list = $image_attachments ? explode(',', $image_attachments) : []; $image_list = $image_attachments ? explode(',', $image_attachments) : [];
} else { } else {
Log::info("Фото не будут добавлены (нет слотов или нет фото)."); Log::channel('vk')->debug('No photos to attach — no slots or no images', ['post_id' => $this->post_id]);
} }
// Собираем все вложения с учетом приоритетов // Собираем все вложения с учетом приоритетов
@@ -99,7 +96,7 @@ class UpdateVkPostJob implements ShouldQueue
$albumLink = "https://vk.ru/album-{$this->public_id}_{$album['id']}"; $albumLink = "https://vk.ru/album-{$this->public_id}_{$album['id']}";
$this->message .= "\n\n[{$albumLink}|Ссылка на все фотографии]"; $this->message .= "\n\n[{$albumLink}|Ссылка на все фотографии]";
} else { } else {
Log::error('Не удалось создать альбом'); Log::channel('vk')->error('Failed to create VK album', ['post_id' => $this->post_id]);
} }
} }
@@ -131,7 +128,7 @@ class UpdateVkPostJob implements ShouldQueue
return "photo{$photo['owner_id']}_{$photo['id']}"; return "photo{$photo['owner_id']}_{$photo['id']}";
}, $photos)); }, $photos));
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error("Ошибка при подготовке фотографий: " . $e->getMessage()); Log::channel('vk')->error('Failed to prepare wall photos', ['error' => $e->getMessage()]);
return ''; return '';
} }
} }
@@ -190,9 +187,9 @@ class UpdateVkPostJob implements ShouldQueue
} }
$uploadedPhotos[] = $saveData['response'][0]; $uploadedPhotos[] = $saveData['response'][0];
Log::info("Фотография загружена. ID: " . $saveData['response'][0]['id']); Log::channel('vk')->debug('Photo uploaded successfully', ['photo_id' => $saveData['response'][0]['id']]);
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error("Ошибка при загрузке {$imagePath}: " . $e->getMessage()); Log::channel('vk')->error('Failed to upload photo', ['path' => $imagePath, 'error' => $e->getMessage()]);
} }
} }
@@ -231,7 +228,7 @@ class UpdateVkPostJob implements ShouldQueue
$attachment = "video{$uploadData['owner_id']}_{$uploadData['video_id']}"; $attachment = "video{$uploadData['owner_id']}_{$uploadData['video_id']}";
$uploadedVideos[] = $attachment; $uploadedVideos[] = $attachment;
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error("Ошибка при загрузке видео {$videoPath}: " . $e->getMessage()); Log::channel('vk')->error('Failed to upload video', ['path' => $videoPath, 'error' => $e->getMessage()]);
} }
} }
@@ -38,7 +38,7 @@ class TgPostPublisher
public function update(array $settings, Post $post): void public function update(array $settings, Post $post): void
{ {
Log::info(json_encode($settings)); Log::channel('vk')->debug('Telegram publisher settings', ['settings' => $settings]);
if ($post->status === PostStatus::PUBLISHED) { if ($post->status === PostStatus::PUBLISHED) {
if ($settings['telegram']) { if ($settings['telegram']) {
$text = $this->generateContentForTg($post->title, $post->content, $post->slug, $post->images); $text = $this->generateContentForTg($post->title, $post->content, $post->slug, $post->images);
+2 -2
View File
@@ -151,7 +151,7 @@ class VkAlbumService
)); ));
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Ошибка при создании альбома: ' . $e->getMessage()); Log::channel('vk')->error('Failed to create VK album', ['error' => $e->getMessage()]);
return [ return [
'success' => false, 'success' => false,
'message' => 'Не удалось создать альбом: ' . $e->getMessage(), 'message' => 'Не удалось создать альбом: ' . $e->getMessage(),
@@ -167,7 +167,7 @@ class VkAlbumService
'group_id' => $group_id, 'group_id' => $group_id,
)); ));
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Ошибка при удалении альбома: ' . $e->getMessage()); Log::channel('vk')->error('Failed to delete VK album', ['error' => $e->getMessage()]);
return [ return [
'success' => false, 'success' => false,
'message' => 'Не удалось удалить альбом: ' . $e->getMessage(), 'message' => 'Не удалось удалить альбом: ' . $e->getMessage(),
+3 -3
View File
@@ -28,7 +28,7 @@ class VkAuthService
return $token; return $token;
} catch (\Exception $e) { } catch (\Exception $e) {
// Обработка ошибок, например, логирование // Обработка ошибок, например, логирование
Log::error('Ошибка при получении токена: ' . $e->getMessage()); Log::channel('vk')->error('Failed to get VK token', ['error' => $e->getMessage()]);
return null; // Или выбросьте исключение, если это необходимо return null; // Или выбросьте исключение, если это необходимо
} }
} }
@@ -143,7 +143,7 @@ class VkAuthService
] ]
); );
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Ошибка при обновлении или вставке токена: ' . $e->getMessage()); Log::channel('vk')->error('Failed to store VK token', ['error' => $e->getMessage()]);
return response()->json([ return response()->json([
'success' => false, 'success' => false,
@@ -181,7 +181,7 @@ class VkAuthService
'message' => 'Запись не найдена для обновления.', 'message' => 'Запись не найдена для обновления.',
], 404); ], 404);
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Ошибка при обновлении токена: ' . $e->getMessage()); Log::channel('vk')->error('Failed to refresh VK token', ['error' => $e->getMessage()]);
return response()->json([ return response()->json([
'success' => false, 'success' => false,
+5 -5
View File
@@ -69,7 +69,7 @@ class VkService
$albumLink = "https://vk.ru/album-{$this->public_id}_{$album['id']}"; $albumLink = "https://vk.ru/album-{$this->public_id}_{$album['id']}";
$message .= "\n[{$albumLink}|Ссылка на все фотографии]"; $message .= "\n[{$albumLink}|Ссылка на все фотографии]";
} else { } else {
Log::error('Не удалось создать альбом'); Log::channel('vk')->error('Failed to create VK album');
} }
} }
} }
@@ -156,7 +156,7 @@ class VkService
return "photo{$photo['owner_id']}_{$photo['id']}"; return "photo{$photo['owner_id']}_{$photo['id']}";
}, $photos)); }, $photos));
} catch (Exception $e) { } catch (Exception $e) {
Log::error("Ошибка: " . $e->getMessage()); Log::channel('vk')->error('Failed to prepare wall photos', ['error' => $e->getMessage()]);
} }
} }
@@ -204,7 +204,7 @@ class VkService
$attachment = "video{$uploadData['owner_id']}_{$uploadData['video_id']}"; $attachment = "video{$uploadData['owner_id']}_{$uploadData['video_id']}";
$uploadedVideos[] = $attachment; $uploadedVideos[] = $attachment;
} catch (Exception $e) { } catch (Exception $e) {
Log::error("Ошибка при загрузке видео {$videoPath}: " . $e->getMessage()); Log::channel('vk')->error('Failed to upload video', ['path' => $videoPath, 'error' => $e->getMessage()]);
} }
} }
@@ -258,10 +258,10 @@ class VkService
// Добавляем данные о загруженной фотографии в массив // Добавляем данные о загруженной фотографии в массив
$uploadedPhotos[] = $saveData['response'][0]; $uploadedPhotos[] = $saveData['response'][0];
Log::info("Фотография успешно загружена. ID: " . $saveData['response'][0]['id']); Log::channel('vk')->debug('Photo uploaded successfully', ['photo_id' => $saveData['response'][0]['id']]);
} catch (Exception $e) { } catch (Exception $e) {
// Логируем ошибку, но продолжаем загрузку остальных изображений // Логируем ошибку, но продолжаем загрузку остальных изображений
Log::error("Ошибка при загрузке изображения {$imagePath}: " . $e->getMessage()); Log::channel('vk')->error('Failed to upload image', ['path' => $imagePath, 'error' => $e->getMessage()]);
} }
} }
+4 -4
View File
@@ -44,7 +44,7 @@ class VkWallService
)); ));
return $post[0]; return $post[0];
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Ошибка при попытке получения айди ' . $e->getMessage()); Log::channel('vk')->error('Failed to get VK post by ID', ['error' => $e->getMessage()]);
} }
} }
@@ -75,7 +75,7 @@ class VkWallService
} }
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Ошибка при создании поста: ' . $e->getMessage()); Log::channel('vk')->error('Failed to create VK wall post', ['error' => $e->getMessage()]);
return [ return [
'success' => false, 'success' => false,
'message' => 'Не удалось создать пост: ' . $e->getMessage(), 'message' => 'Не удалось создать пост: ' . $e->getMessage(),
@@ -104,7 +104,7 @@ class VkWallService
), ),
); );
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Ошибка при обновлении новости SDK: ' . $e->getMessage()); Log::channel('vk')->error('Failed to update VK post via SDK', ['error' => $e->getMessage()]);
return [ return [
'success' => false, 'success' => false,
'message' => 'Не удалось обновить новость SDK: ' . $e->getMessage(), 'message' => 'Не удалось обновить новость SDK: ' . $e->getMessage(),
@@ -133,7 +133,7 @@ class VkWallService
throw new \Exception('Ошибка API: ' . json_encode($response->json())); throw new \Exception('Ошибка API: ' . json_encode($response->json()));
} }
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Ошибка при удалении поста: ' . $e->getMessage()); Log::channel('vk')->error('Failed to delete VK post', ['error' => $e->getMessage()]);
return [ return [
'success' => false, 'success' => false,
'message' => 'Не удалось удалить пост: ' . $e->getMessage(), 'message' => 'Не удалось удалить пост: ' . $e->getMessage(),