본문 바로가기
리눅스/Part3. Ch06. 로깅

05. (실습) systemd 등록 어플리케이션의 로그 저장

by Engineer-Lee 2022. 12. 15.
반응형

Systemd 기반의 앱 구동 및 로그 관리

- FastAPI 기반 HelloWorld 앱 작성
- systemd 데몬 형태로 앱 구동
- journalctl 로 로그 출력 확인
- rsyslog 설정으로 별도의 로그 파일로 저장
. /var/log/hello.log
- 로그 로테이트 설정
. logrotate.d 디렉토리에 HelloWorld 앱용 설정 추가


실습 링크: https://github.com/go4real/linux_campus/blob/main/Part3/Ch06_05/systemd_logging.md


[실습] systemd 서비스 구동 앱의 로그 출력하기


0. pip3 패키지 설치

sudo apt update
sudo apt install python3-pip


1. 파이썬 패키지 설치
 + uvicorn[standard], gunicorn

sudo pip3 install "uvicorn[standard]" gunicorn fastapi


2. fastapi 앱 파일 생성
 + mkdir ~/systemd_demo
 + vim /home/ubuntu/systemd_demo/main.py
 + 자동 줄바꿈 해제 :set paste 후 복사 붙여넣기

from fastapi import FastAPI
from datetime import datetime
import logging
from logging.handlers import SysLogHandler

log = logging.getLogger('demo')
log.setLevel(logging.DEBUG)
handler = SysLogHandler(address='/dev/log',
        facility=SysLogHandler.LOG_LOCAL7)
handler.setFormatter(logging.Formatter('hello: %(message)s'))
log.addHandler(handler)

app = FastAPI()


@app.get("/")
def read_root():
    now = datetime.now()
    current_time = now.strftime("%H:%M:%S")
    log.debug('[{}] Hello World'.format(current_time))
    return {"Hello": "World"}


3. system unit 파일 생성
 + sudo vim /etc/systemd/system/hello.service

[Unit]
Description=HelloWorld
After=network.target

[Service]
WorkingDirectory=/home/ubuntu/systemd_demo
ExecStart=gunicorn main:app --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000
Restart=on-failure
RestartSec=5s
SyslogIdentifier=gunicorn
SyslogFacility=local7

[Install]
WantedBy=multi-user.target


4. hello service 시작 및 동작 상태 확인

sudo systemctl daemon-reload
sudo systemctl restart hello
sudo systemctl status hello


5. 테스트 

curl localhost:8000
sudo journalctl -u hello -n 5


6. rsyslog 설정  (/var/log/에 파일로 저장)
 + sudo vim /etc/rsyslog.d/30-hello.conf

 local7.*             /var/log/hello.log


7. rsyslog 데몬 재시작

sudo systemctl restart rsyslog


8. 로그 이벤트 생성 및 로그 파일 저장 내용 확인

sudo systemctl restart hello
curl localhost:8000
cat /var/log/hello.log


9. 로그 로테이트 설정
sudo vim /etc/logrotate.d/hello

/var/log/hello.log {
  daily
  rotate 14
  missingok
  notifempty
  copytruncate
  compress
  delaycompress
}


## [실습정리] 자원삭제

1. 인스턴스 삭제

 


Systemd의 로깅 시스템(Journald)으로 앱 로그 관리

- FastAPI 기반 HelloWorld 앱 작성
- systemd 데몬 형태로 앱 구동
- journalctl 로 로그 출력 확인
- rsyslog 설정으로 별도의 로그 파일로 저장
. /var/log/hello.log
- 로그 로테이트 설정
. logrotate.d 디렉토리에 HelloWorld 앱용 설정 추가


정리

- 앱을 Systemd 서비스 형태로 구동
- 로컬에 저장되는 로그의 효율적인 관리를 위해 Journald, Rsyslogd를 활용
- 저장된 로그 파일 관리를 위해 Logrotate 설정

반응형

'리눅스 > Part3. Ch06. 로깅' 카테고리의 다른 글

04. 대규모 로그 관리  (0) 2022.12.14
03. 로그파일 관리  (0) 2022.12.14
02. syslog의 이해  (0) 2022.12.14
01. 리눅스 로깅 이해  (0) 2022.12.14