PHP 로그 파일 용량 초과 문제 해결하기

프리터코더·2025년 6월 3일
0

php 문제 해결

목록 보기
60/79

PHP 애플리케이션을 운영하다 보면 로그 파일이 급격히 커져서 디스크 공간을 모두 차지하는 문제가 발생할 수 있습니다. 이런 상황을 예방하고 해결하는 방법들을 알아보겠습니다.

1. 로그 로테이션 설정

가장 기본적인 해결책은 로그 로테이션을 설정하는 것입니다.

/var/log/php/app.log {
    daily
    rotate 7
    compress
    delaycompress
    missingok
    notifempty
    create 644 www-data www-data
}

2. 파일 크기 기반 로그 분할

<?php
class Logger {
    private $maxFileSize = 10 * 1024 * 1024; // 10MB
    private $logFile;
    
    public function log($message) {
        if (file_exists($this->logFile) && filesize($this->logFile) > $this->maxFileSize) {
            $this->rotateLog();
        }
        file_put_contents($this->logFile, date('Y-m-d H:i:s') . " - $message\n", FILE_APPEND);
    }
    
    private function rotateLog() {
        rename($this->logFile, $this->logFile . '.' . date('YmdHis'));
    }
}

3. 로그 레벨 조정

불필요한 로그를 줄이기 위해 로그 레벨을 조정합니다.

<?php
// 개발환경
if ($_ENV['APP_ENV'] === 'development') {
    error_reporting(E_ALL);
    ini_set('log_errors', 1);
} else {
    // 운영환경에서는 중요한 에러만 로깅
    error_reporting(E_ERROR | E_WARNING);
}

4. 오래된 로그 파일 자동 삭제

<?php
$logDir = '/var/log/php/';
$daysToKeep = 30;

$files = glob($logDir . '*.log.*');
foreach ($files as $file) {
    if (filemtime($file) < time() - ($daysToKeep * 24 * 60 * 60)) {
        unlink($file);
    }
}

5. 조건부 로깅

중요하지 않은 로그는 조건부로 기록합니다.

<?php
class ConditionalLogger {
    public function debugLog($message) {
        // 디버그 로그는 특정 조건에서만 기록
        if ($_ENV['DEBUG_MODE'] === 'true' || $this->isErrorCondition()) {
            error_log($message);
        }
    }
    
    private function isErrorCondition() {
        return error_get_last() !== null;
    }
}

6. 외부 로깅 서비스 활용

로컬 파일 대신 외부 서비스를 사용합니다.

<?php
class RemoteLogger {
    private $endpoint;
    
    public function log($level, $message) {
        $data = [
            'level' => $level,
            'message' => $message,
            'timestamp' => time()
        ];
        
        // 비동기로 전송하여 성능 영향 최소화
        $this->sendAsync($data);
    }
    
    private function sendAsync($data) {
        $cmd = "curl -X POST -H 'Content-Type: application/json' -d '" . 
               json_encode($data) . "' " . $this->endpoint . " > /dev/null 2>&1 &";
        exec($cmd);
    }
}

7. 메모리 기반 로그 버퍼링

<?php
class BufferedLogger {
    private $buffer = [];
    private $bufferSize = 100;
    
    public function log($message) {
        $this->buffer[] = $message;
        
        if (count($this->buffer) >= $this->bufferSize) {
            $this->flush();
        }
    }
    
    private function flush() {
        file_put_contents('/var/log/app.log', implode("\n", $this->buffer) . "\n", FILE_APPEND);
        $this->buffer = [];
    }
    
    public function __destruct() {
        if (!empty($this->buffer)) {
            $this->flush();
        }
    }
}

이러한 방법들을 조합하여 사용하면 로그 파일 용량 문제를 효과적으로 관리할 수 있습니다. 특히 운영 환경에서는 로그 로테이션과 자동 정리 스크립트를 cron으로 설정하는 것을 권장합니다.

profile
일용직 개발자. freetercoder@gmail.com

0개의 댓글