본문 바로가기

스크립트

Perl로 Apache 로그 자동 압축하기 - 오래된 로그를 bzip2로 압축하는 스크립트

728x90
반응형

Perl로 Apache 로그 자동 압축하기 - 오래된 로그를 bzip2로 압축하는 스크립트

compressLog.pl은 Apache 로그 디렉터리를 주기적으로 검색하여 오래된 로그를 bzip2 형식으로 압축하는 Perl 기반 로그 관리 스크립트입니다.

전체적인 구조

Apache Log
  │
  ▼
/var/log/httpd/
  │
  ▼
Log File 검색
  │
  ▼
7일 이전 파일 확인
  │
  ▼
bzip2 압축
  │
  ▼
*.log → *.log.bz2
  │
  ▼
백업 시스템 전송
  │
  ▼
백업 완료 후 보관 기간 경과
  │
  ▼
오래된 로그 삭제

대상 디렉토리

/var/log/httpd/

파일

*.log
*.map
*.webdocu

스크립트 작성

vim compressLog.pl
#!/usr/bin/perl
use strict;
use warnings;
use Time::Local;

my $robot_pid = "/home/ncadmin/CompressLog.pid";
if (open my $pid_fh, '>', $robot_pid) {
    print $pid_fh $$;
    close($pid_fh);
} else {
    warn "Could not open PID file $robot_pid: $!";
}

my $log_path = "/home/ncadmin/CompressLog.log";
open my $log_fh, '>>', $log_path or die "Can't open log file $log_path: $!";

# 시작 시간 기록
my ($sec, $min, $hour, $mday, $mon, $year) = (localtime())[0..5];
printf $log_fh "CompressLog_ROBOT START TIME : %04d-%02d-%02d %02d:%02d:%02d\n", 
    $year + 1900, $mon + 1, $mday, $hour, $min, $sec;

## 설정 값
my $INTERVAL_COM  = 7;                      # 7일 이전 파일 압축
my $INTERVAL_DEL  = 30;                     # 30일 이전 파일 삭제
my $REMOVE_PATH   = "/usr/local/apache/logs/"; # 삭제 대상 디렉토리 경로
my $BZIP          = "/usr/bin/bzip2";
my $RM            = "/bin/rm";

my @PATH_LIST = (
    '/var/log/httpd/',
    $REMOVE_PATH, # 삭제 대상 경로도 탐색 목록에 포함 (필요에 따라 분리 가능)
);

# 기준 시간 계산 (현재 시간 기준 초(sec) 단위 차감)
my $cutoff_time_com = time - ($INTERVAL_COM * 24 * 60 * 60);
my $cutoff_time_del = time - ($INTERVAL_DEL * 24 * 60 * 60);

foreach my $path (@PATH_LIST) {
    unless (opendir my $dir, $path) {
        warn "Can't open directory $path: $!";
        next;
    }
    my @LogFile = readdir $dir;
    closedir($dir);

    foreach my $file (@LogFile) {
        # 숨김 파일 및 특수 디렉토리 제외
        next if $file =~ /^\./;

        my $full_path = $path . $file;
        my @stat_file = stat($full_path);
        next unless @stat_file;

        my $file_mtime = $stat_file[9]; # 파일 수정 시간 (Epoch 타임스탬프)

        # 1. 압축 대상 파일 확인 (*.log, *.map, *.webdocu 이며 숫자가 포함된 경우)
        if ((($file =~ /\.log$/) || ($file =~ /\.map$/) || ($file =~ /\.webdocu$/)) && ($file =~ /[0-9]/)) {
            if ($file_mtime <= $cutoff_time_com) {
                system($BZIP, $full_path);
                print $log_fh "$BZIP $full_path\n";
            }
        }
        
        # 2. 삭제 대상 파일 확인 (지정된 경로이고, 확장자가 .bz 또는 .bz2 이며 숫자가 포함된 경우)
        elsif (($path eq $REMOVE_PATH) && (($file =~ /\.bz2$/) || ($file =~ /\.bz$/)) && ($file =~ /[0-9]/)) {
            if ($file_mtime <= $cutoff_time_del) {
                system($RM, $full_path);
                print $log_fh "$RM $full_path\n";
            }
        }
    }
}

# 종료 시간 기록
($sec, $min, $hour, $mday, $mon, $year) = (localtime())[0..5];
printf $log_fh "CompressLog_ROBOT END TIME : %04d-%02d-%02d %02d:%02d:%02d\n", 
    $year + 1900, $mon + 1, $mday, $hour, $min, $sec;

close($log_fh);

스크립트 실행

권한 설정

chmod 755 /home/ncadmin/compressLog.pl

Perl 인터프리터를 직접 실행

/usr/bin/perl /home/ncadmin/compressLog.pl

Cron을 이용한 자동 실행

crontab -e
0 1 * * * /usr/bin/perl /home/ncadmin/compressLog.pl

로그 확인

tail -f /home/ncadmin/CompressLog.log

 

728x90
반응형

'스크립트' 카테고리의 다른 글

myip 스크립트  (0) 2020.11.04
쉘 프로그래밍  (0) 2020.09.04
MariaDB_alldump.sh  (0) 2018.06.27
SSL 인증서 만료일 체크 스크립트(90일 이하 도메인 알람)  (0) 2018.05.24
[스크립트] thread dump && heap dump  (0) 2016.11.26