본문 바로가기

리눅스

우분투에서 Logrotate를 설정하는 방법

반응형

우분투에서 Logrotate를 설정하는 방법

Logrotate는 로그 파일의 크기 증가를 방지하고 디스크 공간을 효율적으로 관리하기 위해 로그 파일을 주기적으로 압축, 이동, 삭제하는 도구입니다.

1. Logrotate 기본 구조 이해

Logrotate는 기본 설정 파일과 개별 설정 파일을 사용합니다.

  • 기본 설정 파일 : /etc/logrotate.conf
  • 개별 애플리케이션 설정 파일 : /etc/logrotate.d

2. Logrotate 기본 설정 파일 확인

/etc/logrotate.conf 파일은 시스템 전체에 적용되는 기본 정책을 정의합니다.

cat /etc/logrotate.conf
# see "man logrotate" for details

# global options do not affect preceding include directives

# rotate log files weekly
weekly

# use the adm group by default, since this is the owning group
# of /var/log/.
su root adm

# keep 4 weeks worth of backlogs
rotate 4

# create new (empty) log files after rotating old ones
create

# use date as a suffix of the rotated file
#dateext

# uncomment this if you want your log files compressed
#compress

# packages drop log rotation information into this directory
include /etc/logrotate.d

# system-specific logs may also be configured here.

3. 애플리케이션별 Logrotate 설정

/etc/logrotate.d/ 디렉토리에 개별 설정 파일을 생성하거나 수정합니다.

 

예: nginx 로그 파일 관리 설정 추가

vim /etc/logrotate.d/nginx
/var/log/nginx/*.log {
    daily                  # 매일 로그 로테이션
    dateext
    rotate 14              # 14회차 보관
    compress               # 압축 활성화
    delaycompress          # 이전 로그는 다음 로테이션 시 압축
    missingok              # 로그 파일이 없어도 에러 없이 진행
    notifempty             # 빈 파일은 무시
    create 0640 nginx adm  # 새 로그 파일 생성 권한 및 소유자 지정
    sharedscripts          # 여러 파일에 대해 postrotate 스크립트 한 번 실행
    postrotate
        if [ -f /var/run/nginx.pid ]; then
            kill -USR1 `cat /var/run/nginx.pid`
        fi
    endscript
}
더보기

---

sudo tee /etc/logrotate.d/nginx > /dev/null <<'EOF'
/var/log/nginx/*.log {
    daily
    dateext
    rotate 14
    missingok
    compress
    delaycompress
    notifempty
    create 640 nginx adm
    sharedscripts
    postrotate
        if [ -f /var/run/nginx.pid ]; then
            kill -USR1 `cat /var/run/nginx.pid`
        fi
    endscript
}
EOF

---

4. Logrotate 테스트

설정이 올바른지 테스트합니다.

  • -d 옵션은 디버그 모드로 실제로 로그 파일을 변경하지 않고 수행 과정을 출력합니다.
sudo logrotate -d /etc/logrotate.conf

5. Logrotate 수동 실행

로그 파일을 즉시 로테이션합니다.

sudo logrotate -f /etc/logrotate.conf
728x90

6. Cron을 통한 Logrotate 자동 실행 확인

Logrotate는 일반적으로 Cron에 의해 자동 실행됩니다.

  • cron 서비스가 실행 중인지 확인
systemctl status cron.service
  • Logrotate 관련 Cron 설정 확인
cat /etc/cron.daily/logrotate
#!/bin/sh

# skip in favour of systemd timer
if [ -d /run/systemd/system ]; then
    exit 0
fi

# this cronjob persists removals (but not purges)
if [ ! -x /usr/sbin/logrotate ]; then
    exit 0
fi

/usr/sbin/logrotate /etc/logrotate.conf
EXITVALUE=$?
if [ $EXITVALUE != 0 ]; then
    /usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]"
fi
exit $EXITVALUE

7. Logrotate 설정 파일 유효성 검사

설정 파일에 오류가 있는지 확인

sudo logrotate -v /etc/logrotate.conf

logrotate 실행 시 unknown user 'nginx' 오류 해결하기

에러 메시지

  • logrotate 설정 파일에서 nginx 사용자로 로그 파일을 생성하려 했지만 시스템에 해당 사용자가 존재하지 않는다.
sudo logrotate -v /etc/logrotate.d/nginx
reading config file /etc/logrotate.d/nginx
error: /etc/logrotate.d/nginx:9 unknown user 'nginx'
error: found error in /var/log/nginx/*.log , skipping
removing last 1 log configs
...
Handling 0 logs

원인 분석

  • 로그 로테이션 이후 새로 생성될 로그 파일의 권한과 소유자 점검
cat /etc/logrotate.d/nginx | grep create
create 640 nginx adm
  • nginx 사용자가 존재하는지 확인
grep 'nginx' /etc/passwd

해결 방법

  • logrotate 설정 파일에서 존재하지 않는 nginx 사용자를, 실제 Nginx 실행 사용자로 변경한다.
sudo vim /etc/logrotate.d/nginx
create 640 www-data adm

동작 확인(Debug/Force)

Debug 모드로 설정 검증

sudo logrotate -d /etc/logrotate.d/nginx
warning: logrotate in debug mode does nothing except printing debug messages!  Consider using verbose mode (-v) instead if this is not what you want.

reading config file /etc/logrotate.d/nginx
Reading state from file: /var/lib/logrotate/status
Allocating hash table for state file, size 64 entries
Creating new state
...
Creating new state

Handling 1 logs
  • -d 옵션은 실제 로테이션은 수행하지 않고 설정과 동작 흐름만 검증한다.
  • 오류 없이 Handling 1 logs가 출력되면 설정 자체는 정상이다

강제 로테이션 실행

sudo logrotate -f /etc/logrotate.d/nginx
  • -f 옵션은 조건과 관계없이 강제로 로그 로테이션을 수행한다.
  • 실제 운영 환경에서는 주의해서 사용하자.

Logrotate 설정이 완료되면 로그 파일이 효율적으로 관리되는지 정기적으로 확인하세요.

 

728x90
반응형