feat(logging): migrate remaining files to app channel — all Log:: calls now use domain channels

This commit is contained in:
F4ilji
2026-07-05 23:32:01 +05:00
parent 6bc1b3e921
commit 769b2ff342
17 changed files with 50 additions and 50 deletions
@@ -66,7 +66,7 @@ class FetchEmailNewsCommand extends ConsoleCommand
return $this->handleSync($fetchEmailNewsAction, $verbose); return $this->handleSync($fetchEmailNewsAction, $verbose);
} catch (EmailFetchException $e) { } catch (EmailFetchException $e) {
$this->error('❌ Ошибка Email: ' . $e->getMessage()); $this->error('❌ Ошибка Email: ' . $e->getMessage());
Log::error('[FetchEmailNewsCommand] EmailFetchException', [ Log::channel('app')->error('EmailFetchException', [
'code' => $e->getCode(), 'code' => $e->getCode(),
'message' => $e->getMessage(), 'message' => $e->getMessage(),
]); ]);
@@ -76,7 +76,7 @@ class FetchEmailNewsCommand extends ConsoleCommand
$this->error('❌ Критическая ошибка: ' . $e->getMessage()); $this->error('❌ Критическая ошибка: ' . $e->getMessage());
$this->warn('Проверьте логи: storage/logs/laravel.log'); $this->warn('Проверьте логи: storage/logs/laravel.log');
Log::error('[FetchEmailNewsCommand] Critical Error', [ Log::channel('app')->error('Critical Error', [
'error' => $e->getMessage(), 'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(), 'trace' => $e->getTraceAsString(),
]); ]);
@@ -57,7 +57,7 @@ class ProcessEmailNewsJob implements ShouldQueue
*/ */
public function handle(FetchEmailNewsAction $fetchEmailNewsAction): void public function handle(FetchEmailNewsAction $fetchEmailNewsAction): void
{ {
Log::info('[ProcessEmailNewsJob] Начало обработки job', [ Log::channel('app')->info('Начало обработки job', [
'job_id' => $this->job?->getJobId() ?? 'unknown', 'job_id' => $this->job?->getJobId() ?? 'unknown',
'attempt' => $this->attempts(), 'attempt' => $this->attempts(),
'memory_limit' => ini_get('memory_limit'), 'memory_limit' => ini_get('memory_limit'),
@@ -66,7 +66,7 @@ class ProcessEmailNewsJob implements ShouldQueue
// Выполняем обработку — если выбросит исключение, Laravel автоматически повторит job // Выполняем обработку — если выбросит исключение, Laravel автоматически повторит job
$result = $fetchEmailNewsAction->run(); $result = $fetchEmailNewsAction->run();
Log::info('[ProcessEmailNewsJob] Обработка завершена успешно', [ Log::channel('app')->info('Обработка завершена успешно', [
'job_id' => $this->job?->getJobId() ?? 'unknown', 'job_id' => $this->job?->getJobId() ?? 'unknown',
'processed_emails' => $result['processed_emails'], 'processed_emails' => $result['processed_emails'],
'created_posts' => $result['created_posts'], 'created_posts' => $result['created_posts'],
@@ -79,7 +79,7 @@ class ProcessEmailNewsJob implements ShouldQueue
// Если были ошибки, логируем их как warning // Если были ошибки, логируем их как warning
if (!empty($result['errors'])) { if (!empty($result['errors'])) {
foreach ($result['errors'] as $error) { foreach ($result['errors'] as $error) {
Log::warning('[ProcessEmailNewsJob] Ошибка обработки письма', [ Log::channel('app')->warning('Ошибка обработки письма', [
'subject' => $error['email_subject'] ?? 'unknown', 'subject' => $error['email_subject'] ?? 'unknown',
'error' => $error['error'], 'error' => $error['error'],
]); ]);
@@ -95,7 +95,7 @@ class ProcessEmailNewsJob implements ShouldQueue
*/ */
public function failed(\Throwable $exception): void public function failed(\Throwable $exception): void
{ {
Log::critical('[ProcessEmailNewsJob] Job окончательно провален', [ Log::channel('app')->critical('Job окончательно провален', [
'total_attempts' => $this->tries, 'total_attempts' => $this->tries,
'error' => $exception->getMessage(), 'error' => $exception->getMessage(),
]); ]);
@@ -43,7 +43,7 @@ class CompressImageTask
{ {
$extension = strtolower($file->getClientOriginalExtension()); $extension = strtolower($file->getClientOriginalExtension());
Log::info('[CompressImageTask] Начало обработки изображения', [ Log::channel('app')->info('Начало обработки изображения', [
'file' => $file->getClientOriginalName(), 'file' => $file->getClientOriginalName(),
'extension' => $extension, 'extension' => $extension,
'size' => $this->formatFileSize($file->getSize()), 'size' => $this->formatFileSize($file->getSize()),
@@ -52,7 +52,7 @@ class CompressImageTask
// Если файл уже меньше порога и это WebP - пропускаем сжатие // Если файл уже меньше порога и это WebP - пропускаем сжатие
if ($file->getSize() <= self::SIZE_THRESHOLD && $extension === 'webp') { if ($file->getSize() <= self::SIZE_THRESHOLD && $extension === 'webp') {
Log::info('[CompressImageTask] Файл уже оптимизирован, пропускаем', [ Log::channel('app')->info('Файл уже оптимизирован, пропускаем', [
'file' => $file->getClientOriginalName(), 'file' => $file->getClientOriginalName(),
]); ]);
@@ -71,7 +71,7 @@ class CompressImageTask
$originalWidth = $img->width(); $originalWidth = $img->width();
$originalHeight = $img->height(); $originalHeight = $img->height();
Log::info('[CompressImageTask] Исходные размеры', [ Log::channel('app')->info('Исходные размеры', [
'width' => $originalWidth, 'width' => $originalWidth,
'height' => $originalHeight, 'height' => $originalHeight,
]); ]);
@@ -83,7 +83,7 @@ class CompressImageTask
$constraint->upsize(); $constraint->upsize();
}); });
Log::info('[CompressImageTask] Изображение ресайзнуто', [ Log::channel('app')->info('Изображение ресайзнуто', [
'new_width' => $img->width(), 'new_width' => $img->width(),
'new_height' => $img->height(), 'new_height' => $img->height(),
]); ]);
@@ -99,7 +99,7 @@ class CompressImageTask
$newSize = filesize($tempPath); $newSize = filesize($tempPath);
Log::info('[CompressImageTask] Сжатие завершено', [ Log::channel('app')->info('Сжатие завершено', [
'original_size' => $this->formatFileSize($file->getSize()), 'original_size' => $this->formatFileSize($file->getSize()),
'compressed_size' => $this->formatFileSize($newSize), 'compressed_size' => $this->formatFileSize($newSize),
'compression_ratio' => round((1 - $newSize / $file->getSize()) * 100, 2) . '%', 'compression_ratio' => round((1 - $newSize / $file->getSize()) * 100, 2) . '%',
@@ -47,7 +47,7 @@ trait MemoryAwareTrait
// Логируем только если превышен порог // Логируем только если превышен порог
if ($currentMemory > $this->memoryLogThreshold) { if ($currentMemory > $this->memoryLogThreshold) {
Log::info('[MemoryMonitor] Использование памяти', [ Log::channel('app')->info('Использование памяти', [
'context' => $context, 'context' => $context,
'current' => round($currentMemory / 1024 / 1024, 2) . 'MB', 'current' => round($currentMemory / 1024 / 1024, 2) . 'MB',
'peak' => round($peakMemory / 1024 / 1024, 2) . 'MB', 'peak' => round($peakMemory / 1024 / 1024, 2) . 'MB',
@@ -75,7 +75,7 @@ trait MemoryAwareTrait
$memoryAfter = round(memory_get_usage(true) / 1024 / 1024, 2); $memoryAfter = round(memory_get_usage(true) / 1024 / 1024, 2);
$freed = round(($memoryBefore - $memoryAfter), 2); $freed = round(($memoryBefore - $memoryAfter), 2);
Log::info('[MemoryMonitor] Сборка мусора выполнена', [ Log::channel('app')->info('Сборка мусора выполнена', [
'memory_before' => $memoryBefore . 'MB', 'memory_before' => $memoryBefore . 'MB',
'memory_after' => $memoryAfter . 'MB', 'memory_after' => $memoryAfter . 'MB',
'freed' => $freed . 'MB', 'freed' => $freed . 'MB',
@@ -18,7 +18,7 @@ class ParseEmailNewsController extends Controller
public function __invoke(Request $request): RedirectResponse public function __invoke(Request $request): RedirectResponse
{ {
try { try {
Log::info('[ParseEmailNewsController] Принудительный запуск парсинга email'); Log::channel('app')->info('Принудительный запуск парсинга email');
$result = $this->fetchEmailNewsAction->run(); $result = $this->fetchEmailNewsAction->run();
@@ -38,13 +38,13 @@ class ParseEmailNewsController extends Controller
"Обработано писем: {$result['processed_emails']}, но новостей не создано" "Обработано писем: {$result['processed_emails']}, но новостей не создано"
); );
} catch (EmailFetchException $e) { } catch (EmailFetchException $e) {
Log::error('[ParseEmailNewsController] EmailFetchException', [ Log::channel('app')->error('EmailFetchException', [
'error' => $e->getMessage(), 'error' => $e->getMessage(),
]); ]);
return redirect()->back()->with('error', $e->getMessage()); return redirect()->back()->with('error', $e->getMessage());
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('[ParseEmailNewsController] Критическая ошибка', [ Log::channel('app')->error('Критическая ошибка', [
'error' => $e->getMessage(), 'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(), 'trace' => $e->getTraceAsString(),
]); ]);
@@ -15,7 +15,7 @@ class ClearStaticSearchCacheAction
Cache::forget(self::CACHE_KEY); Cache::forget(self::CACHE_KEY);
return true; return true;
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Cache clear error: ' . $e->getMessage()); Log::channel('app')->error('Cache clear error: ' . $e->getMessage());
return false; return false;
} }
} }
@@ -47,7 +47,7 @@ class SearchStaticFilesAction
return app(PaginateSearchResultsTask::class)->run($results, $page, self::PER_PAGE, $categories); return app(PaginateSearchResultsTask::class)->run($results, $page, self::PER_PAGE, $categories);
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Search error: ' . $e->getMessage()); Log::channel('app')->error('Search error: ' . $e->getMessage());
return [ return [
'data' => [], 'data' => [],
'meta' => [ 'meta' => [
@@ -77,7 +77,7 @@ class SearchStaticFilesAction
return null; return null;
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Failed to get H1: ' . $e->getMessage()); Log::channel('app')->error('Failed to get H1: ' . $e->getMessage());
return null; return null;
} }
} }
@@ -24,7 +24,7 @@ class BuildStaticFileIndexTask
$directory = public_path(self::FILES_DIR); $directory = public_path(self::FILES_DIR);
if (!is_dir($directory)) { if (!is_dir($directory)) {
Log::error("Directory not found: {$directory}"); Log::channel('app')->error("Directory not found: {$directory}");
return []; return [];
} }
@@ -51,7 +51,7 @@ class BuildStaticFileIndexTask
return $index; return $index;
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Index creation error: ' . $e->getMessage()); Log::channel('app')->error('Index creation error: ' . $e->getMessage());
return []; return [];
} }
}); });
@@ -80,7 +80,7 @@ class BuildStaticFileIndexTask
return null; return null;
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Failed to get H1: ' . $e->getMessage()); Log::channel('app')->error('Failed to get H1: ' . $e->getMessage());
return null; return null;
} }
} }
@@ -14,7 +14,7 @@ class GetStaticFileCategoriesTask
try { try {
$file = public_path(self::FILES_DIR . '/' . 'index.html'); $file = public_path(self::FILES_DIR . '/' . 'index.html');
if (!file_exists($file)) { if (!file_exists($file)) {
Log::error("Category index file not found: {$file}"); Log::channel('app')->error("Category index file not found: {$file}");
return []; return [];
} }
@@ -24,7 +24,7 @@ class GetStaticFileCategoriesTask
$dropdownMenu = $document->first('ul.dropdown-menu'); $dropdownMenu = $document->first('ul.dropdown-menu');
if ($dropdownMenu === null) { if ($dropdownMenu === null) {
Log::warning("Dropdown menu not found in category index file: {$file}"); Log::channel('app')->warning("Dropdown menu not found in category index file: {$file}");
return []; return [];
} }
@@ -38,7 +38,7 @@ class GetStaticFileCategoriesTask
return $categories; return $categories;
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Error extracting categories: ' . $e->getMessage()); Log::channel('app')->error('Error extracting categories: ' . $e->getMessage());
return []; return [];
} }
} }
+7 -7
View File
@@ -34,7 +34,7 @@ class ImportApiDataPost implements ShouldQueue
// Получаем первую страницу данных // Получаем первую страницу данных
$response = Http::get(config('TRANSFER_PROXY_URL') . '/api/posts')->object(); $response = Http::get(config('TRANSFER_PROXY_URL') . '/api/posts')->object();
$last_page = $response->last_page; $last_page = $response->last_page;
Log::info('Last page: ' . $last_page); Log::channel('app')->info('Last page: ' . $last_page);
// Проходим по всем страницам // Проходим по всем страницам
for ($page = 1; $page <= $last_page; $page++) { for ($page = 1; $page <= $last_page; $page++) {
@@ -43,7 +43,7 @@ class ImportApiDataPost implements ShouldQueue
// Обрабатываем каждую запись // Обрабатываем каждую запись
foreach ($results as $post) { foreach ($results as $post) {
Log::info('Processing post ID: ' . $post->ID); Log::channel('app')->info('Processing post ID: ' . $post->ID);
try { try {
// Получаем массив изображений // Получаем массив изображений
@@ -52,7 +52,7 @@ class ImportApiDataPost implements ShouldQueue
// Проверяем, есть ли изображения // Проверяем, есть ли изображения
if (empty($images)) { if (empty($images)) {
Log::warning('No images found for post ID: ' . $post->ID); Log::channel('app')->warning('No images found for post ID: ' . $post->ID);
} else { } else {
// Проходимся по массиву изображений // Проходимся по массиву изображений
foreach ($images as $image) { foreach ($images as $image) {
@@ -60,13 +60,13 @@ class ImportApiDataPost implements ShouldQueue
if (isset($image->SUBDIR) && isset($image->FILE_NAME)) { if (isset($image->SUBDIR) && isset($image->FILE_NAME)) {
$imagePaths[] = 'upload/' . $image->SUBDIR . '/' . $image->FILE_NAME; $imagePaths[] = 'upload/' . $image->SUBDIR . '/' . $image->FILE_NAME;
} else { } else {
Log::warning('Image data is incomplete for post ID: ' . $post->ID); Log::channel('app')->warning('Image data is incomplete for post ID: ' . $post->ID);
} }
} }
} }
// Логируем пути к изображениям для отладки // Логируем пути к изображениям для отладки
Log::info('Image paths for post ID ' . $post->ID . ': ' . json_encode($imagePaths)); Log::channel('app')->debug('Image paths for post', ['post_id' => $post->ID, 'paths' => $imagePaths]);
// Обработка контента поста // Обработка контента поста
$content = strip_tags($post->DETAIL_TEXT, '<a>'); $content = strip_tags($post->DETAIL_TEXT, '<a>');
@@ -110,12 +110,12 @@ class ImportApiDataPost implements ShouldQueue
$this->createSeo($createdPost); $this->createSeo($createdPost);
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Error importing post ID: ' . $post->ID . ' - ' . $e->getMessage()); Log::channel('app')->error('Error importing post ID: ' . $post->ID . ' - ' . $e->getMessage());
} }
} }
} }
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Error fetching posts: ' . $e->getMessage()); Log::channel('app')->error('Error fetching posts: ' . $e->getMessage());
} }
} }
+1 -1
View File
@@ -79,7 +79,7 @@ class ImportUsers implements ShouldQueue
} }
} }
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Error fetching posts: ' . $e->getMessage()); Log::channel('app')->error('Error fetching posts: ' . $e->getMessage());
} }
} }
} }
+2 -2
View File
@@ -32,7 +32,7 @@ class RunBackup implements ShouldQueue
]); ]);
// Логируем вывод // Логируем вывод
Log::info('Backup command output: ' . Artisan::output()); Log::channel('app')->info('Backup command output: ' . Artisan::output());
Log::error('Backup command exit code: ' . $exitCode); Log::channel('app')->error('Backup command exit code: ' . $exitCode);
} }
} }
@@ -38,9 +38,9 @@ class PostSliderService
]); ]);
$post->slide()->save($slide); $post->slide()->save($slide);
Log::info('Slide created successfully', ['postTitle' => $this->post->title]); Log::channel('app')->info('Slide created successfully', ['postTitle' => $this->post->title]);
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Failed to create slide', [ Log::channel('app')->error('Failed to create slide', [
'postTitle' => $this->post->title, 'postTitle' => $this->post->title,
'error' => $e->getMessage(), 'error' => $e->getMessage(),
]); ]);
@@ -71,7 +71,7 @@ class PostSliderService
]); ]);
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Failed to update MainSlider', [ Log::channel('app')->error('Failed to update MainSlider', [
'postTitle' => $this->post->title, 'postTitle' => $this->post->title,
'error' => $e->getMessage(), 'error' => $e->getMessage(),
]); ]);
@@ -61,7 +61,7 @@ class StaticFileSearch
return $this->paginateResults($results, $page, $categories); return $this->paginateResults($results, $page, $categories);
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Search error: ' . $e->getMessage()); Log::channel('app')->error('Search error: ' . $e->getMessage());
return [ return [
'data' => [], 'data' => [],
'meta' => [ 'meta' => [
@@ -103,7 +103,7 @@ class StaticFileSearch
$directory = public_path(self::FILES_DIR); $directory = public_path(self::FILES_DIR);
if (!is_dir($directory)) { if (!is_dir($directory)) {
Log::error("Directory not found: {$directory}"); Log::channel('app')->error("Directory not found: {$directory}");
return []; return [];
} }
@@ -130,7 +130,7 @@ class StaticFileSearch
return $index; return $index;
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Index creation error: ' . $e->getMessage()); Log::channel('app')->error('Index creation error: ' . $e->getMessage());
return []; return [];
} }
}); });
@@ -181,7 +181,7 @@ class StaticFileSearch
Cache::forget(self::CACHE_KEY); Cache::forget(self::CACHE_KEY);
return true; return true;
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Cache clear error: ' . $e->getMessage()); Log::channel('app')->error('Cache clear error: ' . $e->getMessage());
return false; return false;
} }
} }
@@ -212,7 +212,7 @@ class StaticFileSearch
return null; return null;
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Failed to get H1: ' . $e->getMessage()); Log::channel('app')->error('Failed to get H1: ' . $e->getMessage());
return null; return null;
} }
} }
@@ -31,7 +31,7 @@ class AdmissionPlanService
config('services.vicon.token') config('services.vicon.token')
); );
if (!is_array($response)) { if (!is_array($response)) {
Log::warning('Unexpected response type in getCampaigns', [ Log::channel('app')->warning('Unexpected response type in getCampaigns', [
'type' => gettype($response), 'type' => gettype($response),
'response' => $response 'response' => $response
]); ]);
@@ -39,7 +39,7 @@ class AdmissionPlanService
return $response; return $response;
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('API call failed in getCampaigns', [ Log::channel('app')->error('API call failed in getCampaigns', [
'error' => $e->getMessage(), 'error' => $e->getMessage(),
'trace' => $e->getTraceAsString() 'trace' => $e->getTraceAsString()
]); ]);
@@ -56,7 +56,7 @@ class AdmissionPlanService
); );
if (!is_object($response)) { if (!is_object($response)) {
Log::warning('Unexpected response type in getAdmissionPlans', [ Log::channel('app')->warning('Unexpected response type in getAdmissionPlans', [
'expected' => 'object', 'expected' => 'object',
'actual' => gettype($response), 'actual' => gettype($response),
'campaign_levels_code' => $campaign_levels_code, 'campaign_levels_code' => $campaign_levels_code,
@@ -68,7 +68,7 @@ class AdmissionPlanService
return $response; return $response;
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('API call failed in getAdmissionPlans', [ Log::channel('app')->error('API call failed in getAdmissionPlans', [
'error' => $e->getMessage(), 'error' => $e->getMessage(),
'campaign_levels_code' => $campaign_levels_code, 'campaign_levels_code' => $campaign_levels_code,
'trace' => $e->getTraceAsString() 'trace' => $e->getTraceAsString()
@@ -137,7 +137,7 @@ class AdmissionPlanService
return $data; return $data;
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Ошибка при вызове API: ' . $e->getMessage()); Log::channel('app')->error('Ошибка при вызове API: ' . $e->getMessage());
throw $e; // Перебрасываем исключение throw $e; // Перебрасываем исключение
} }
} }
@@ -81,7 +81,7 @@ class DirectionStudyService
return $data; return $data;
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Ошибка при вызове API: ' . $e->getMessage()); Log::channel('app')->error('API call failed', ['error' => $e->getMessage()]);
throw $e; // Перебрасываем исключение throw $e; // Перебрасываем исключение
} }
} }
@@ -50,7 +50,7 @@ class EducationalProgramService
return $data; return $data;
} catch (\Exception $e) { } catch (\Exception $e) {
Log::error('Ошибка при вызове API: ' . $e->getMessage()); Log::channel('app')->error('API call failed', ['error' => $e->getMessage()]);
throw $e; // Перебрасываем исключение throw $e; // Перебрасываем исключение
} }
} }