File: /var/www/vhost/disk-apps/teamdemo.sports-crowd.com/app/Console/Commands/ArchiveAndDeleteOldLogs.php
<?php
namespace App\Console\Commands;
use App\ActivityLog;
use App\ErpLog;
use App\Log;
use App\Notification;
use App\SystemLog;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
class ArchiveAndDeleteOldLogs extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'sportscrowd:archiveAndDeleteOldLogs';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Tarea encargada de archivar en S3 y eliminar definitivamente los logs más antiguos de 2 años';
protected $now;
protected $date;
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$this->now = Carbon::now();
$this->date = $this->now->subYears(2)->endOfMonth();
$this->info("Archivando y eliminando logs con fecha anterior a: $this->date");
$this->archiveSystemLogs();
$this->info("Proceso de archivado y eliminación de system logs completado.");
$this->archiveLogs();
$this->info("Proceso de archivado y eliminación de logs completado.");
$this->archiveErpLogs();
$this->info("Proceso de archivado y eliminación de erp logs completado.");
$this->archiveActivityLogs();
$this->info("Proceso de archivado y eliminación de activity log completado.");
$this->archiveNotifications();
$this->info("Proceso de archivado y eliminación de notifications completado.");
return 0;
}
private function archiveSystemLogs()
{
$context = 'system_logs';
// Crear nombre de archivo basado en el mes
$month = $this->date->format('Y_m');
$filename = storage_path("app/{$context}_{$month}.jsonl");
$gzFilename = $filename . '.gz';
// Abrir archivo gzip para escritura
$gzHandle = gzopen($gzFilename, 'w9'); // 9 = máxima compresión
$count = 0;
// Extraer y procesar logs eliminados antes de la fecha
SystemLog::onlyTrashed()
->where('deleted_at', '<', $this->date)
->orderBy('id')
->chunkById(1000, function ($logs) use (&$gzHandle, &$count) {
foreach ($logs as $log) {
$data = is_string($log->data) ? json_decode($log->data, true) : $log->data;
$line = json_encode([
'id' => $log->id,
'data' => $data,
'origin' => $log->origin,
'user_id' => $log->user_id,
'created_at' => $log->created_at,
'deleted_at' => $log->deleted_at,
]);
gzwrite($gzHandle, $line . "\n");
}
$count += $logs->count();
// Borrado físico
SystemLog::whereIn('id', $logs->pluck('id'))->forceDelete();
});
$this->info("Se eliminaron definitivamente $count {$context}.");
gzclose($gzHandle);
// Subir archivo a S3
$s3Path = "{$context}/{$context}_{$month}.jsonl.gz";
Storage::disk('s3')->put(config('s3.default') . '/logs_archived/' . $s3Path, fopen($gzFilename, 'r+'), 'public');
// Eliminar archivo temporal local
unlink($gzFilename);
$this->info("Archivo mensual archivado en S3: {$s3Path}");
}
private function archiveLogs()
{
$context = 'logs';
// Crear nombre de archivo basado en el mes
$month = $this->date->format('Y_m');
$filename = storage_path("app/{$context}_{$month}.jsonl");
$gzFilename = $filename . '.gz';
// Abrir archivo gzip para escritura
$gzHandle = gzopen($gzFilename, 'w9'); // 9 = máxima compresión
$count = 0;
// Extraer y procesar logs eliminados antes de la fecha
Log::onlyTrashed()
->where('deleted_at', '<', $this->date)
->orderBy('id')
->chunkById(1000, function ($logs) use (&$gzHandle, &$count) {
foreach ($logs as $log) {
$data = is_string($log->data_operation) ? json_decode($log->data_operation, true) : $log->data_operation;
$line = json_encode([
'id' => $log->id,
'description_operation' => $log->description_operation,
'data_operation' => $data,
'task' => $log->task,
'module_id' => $log->module_id,
'user_id' => $log->user_id,
'created_at' => $log->created_at,
'deleted_at' => $log->deleted_at,
]);
gzwrite($gzHandle, $line . "\n");
}
$count += $logs->count();
// Borrado físico
Log::whereIn('id', $logs->pluck('id'))->forceDelete();
});
$this->info("Se eliminaron definitivamente $count {$context}.");
gzclose($gzHandle);
// Subir archivo a S3
$s3Path = "{$context}/{$context}_{$month}.jsonl.gz";
Storage::disk('s3')->put(config('s3.default') . '/logs_archived/' . $s3Path, fopen($gzFilename, 'r+'), 'public');
// Eliminar archivo temporal local
unlink($gzFilename);
$this->info("Archivo mensual archivado en S3: {$s3Path}");
}
private function archiveErpLogs()
{
$context = 'erp_logs';
// Crear nombre de archivo basado en el mes
$month = $this->date->format('Y_m');
$filename = storage_path("app/{$context}_{$month}.jsonl");
$gzFilename = $filename . '.gz';
// Abrir archivo gzip para escritura
$gzHandle = gzopen($gzFilename, 'w9'); // 9 = máxima compresión
$count = 0;
// Extraer y procesar logs eliminados antes de la fecha
ErpLog::onlyTrashed()
->where('deleted_at', '<', $this->date)
->orderBy('id')
->chunkById(1000, function ($logs) use (&$gzHandle, &$count) {
foreach ($logs as $log) {
$data = is_string($log->data) ? json_decode($log->data, true) : $log->data;
$line = json_encode([
'id' => $log->id,
'origin' => $log->origin,
'action' => $log->action,
'origin_class' => $log->origin_class,
'data' => $data,
'transaction_id' => $log->transaction_id,
'message' => $log->message,
'resolved' => $log->resolved,
'created_at' => $log->created_at,
'deleted_at' => $log->deleted_at,
]);
gzwrite($gzHandle, $line . "\n");
}
$count += $logs->count();
// Borrado físico
ErpLog::whereIn('id', $logs->pluck('id'))->forceDelete();
});
$this->info("Se eliminaron definitivamente $count {$context}.");
gzclose($gzHandle);
// Subir archivo a S3
$s3Path = "{$context}/{$context}_{$month}.jsonl.gz";
Storage::disk('s3')->put(config('s3.default') . '/logs_archived/' . $s3Path, fopen($gzFilename, 'r+'), 'public');
// Eliminar archivo temporal local
unlink($gzFilename);
$this->info("Archivo mensual archivado en S3: {$s3Path}");
}
private function archiveActivityLogs()
{
$context = 'activity_log';
// Crear nombre de archivo basado en el mes
$month = $this->date->format('Y_m');
$filename = storage_path("app/{$context}_{$month}.jsonl");
$gzFilename = $filename . '.gz';
// Abrir archivo gzip para escritura
$gzHandle = gzopen($gzFilename, 'w9'); // 9 = máxima compresión
$count = 0;
// Extraer y procesar logs eliminados antes de la fecha
ActivityLog::onlyTrashed()
->where('deleted_at', '<', $this->date)
->orderBy('id')
->chunkById(1000, function ($logs) use (&$gzHandle, &$count) {
foreach ($logs as $log) {
$properties = is_string($log->properties) ? json_decode($log->properties, true) : $log->properties;
$line = json_encode([
'id' => $log->id,
'log_name' => $log->log_name,
'description' => $log->description,
'subject_type' => $log->subject_type,
'subject_id' => $log->subject_id,
'causer_type' => $log->causer_type,
'causer_id' => $log->causer_id,
'properties' => $properties,
'created_at' => $log->created_at,
'deleted_at' => $log->deleted_at,
]);
gzwrite($gzHandle, $line . "\n");
}
$count += $logs->count();
// Borrado físico
ActivityLog::whereIn('id', $logs->pluck('id'))->forceDelete();
});
$this->info("Se eliminaron definitivamente $count {$context}.");
gzclose($gzHandle);
// Subir archivo a S3
$s3Path = "{$context}/{$context}_{$month}.jsonl.gz";
Storage::disk('s3')->put(config('s3.default') . '/logs_archived/' . $s3Path, fopen($gzFilename, 'r+'), 'public');
// Eliminar archivo temporal local
unlink($gzFilename);
$this->info("Archivo mensual archivado en S3: {$s3Path}");
}
private function archiveNotifications()
{
$context = 'notifications';
// Crear nombre de archivo basado en el mes
$month = $this->date->format('Y_m');
$filename = storage_path("app/{$context}_{$month}.jsonl");
$gzFilename = $filename . '.gz';
// Abrir archivo gzip para escritura
$gzHandle = gzopen($gzFilename, 'w9'); // 9 = máxima compresión
$count = 0;
// Extraer y procesar notificaciones eliminados antes de la fecha
Notification::onlyTrashed()
->where('deleted_at', '<', $this->date)
->orderBy('id')
->chunkById(1000, function ($notifications) use (&$gzHandle, &$count) {
foreach ($notifications as $notification) {
$line = json_encode([
'id' => $notification->id,
'message' => $notification->message,
'when_send' => $notification->when_send,
'is_pending' => $notification->is_pending,
'admin_id' => $notification->admin_id,
'user_id' => $notification->user_id,
'link' => $notification->link,
'reference_onesignal_notification_id' => $notification->reference_onesignal_notification_id,
'created_at' => $notification->created_at,
'deleted_at' => $notification->deleted_at,
]);
gzwrite($gzHandle, $line . "\n");
}
$count += $notifications->count();
// Borrado físico
Notification::whereIn('id', $notifications->pluck('id'))->forceDelete();
});
$this->info("Se eliminaron definitivamente $count {$context}.");
gzclose($gzHandle);
// Subir archivo a S3
$s3Path = "{$context}/{$context}_{$month}.jsonl.gz";
Storage::disk('s3')->put(config('s3.default') . '/logs_archived/' . $s3Path, fopen($gzFilename, 'r+'), 'public');
// Eliminar archivo temporal local
unlink($gzFilename);
$this->info("Archivo mensual archivado en S3: {$s3Path}");
}
}