Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python으로 UNIX syslog 시스템 로그 기록하기 – syslog 모듈 완벽 가이드

UNIX 시스템의 syslog 라이브러리를 활용해 시스템 로그를 기록하고 싶다면, 파이썬에서 기본 제공하는 syslog 모듈을 사용하면 됩니다. 이 모듈은 UNIX syslog 라이브러리의 주요 기능을 그대로 파이썬 인터페이스로 감싸고 있어, 별도의 외부 라이브러리 설치 없이 손쉽게 시스템 로거와 연동할 수 있습니다.

syslog 모듈 가져오기

모듈을 사용하려면 먼저 프로그램 상단에서 아래와 같이 임포트합니다.

import syslog

주요 메서드 살펴보기

1. syslog.syslog(message) / syslog.syslog(priority, message)

문자열 형태의 메시지를 시스템 로거(system logger)로 전송하는 핵심 메서드입니다. 모든 메시지에는 우선순위(priority)가 부여되며, 두 번째 형태처럼 priority 인자를 함께 전달하면 해당 메시지의 중요도를 직접 지정할 수 있습니다.

2. syslog.openlog([ident[, logoption[, facility]]])

이후 호출되는 syslog 함수들의 로깅 옵션을 설정합니다. ident 인자는 문자열로, 여기에 지정한 값이 모든 로그 메시지 앞에 접두사처럼 붙습니다. 일반적으로 프로그램 이름을 넣어 어떤 프로세스가 남긴 로그인지 식별하기 쉽게 만듭니다.

3. syslog.closelog()

syslog 모듈을 초기 상태로 되돌립니다. 모듈을 처음 임포트했을 때의 상태로 리셋되며, 로깅 세션을 깔끔하게 종료할 때 유용합니다.

4. syslog.setlogmask(maskpri)

우선순위 마스크(priority mask)를 maskpri 값으로 설정하고, 변경 이전의 마스크 값을 반환합니다. 이 마스크를 활용하면 특정 우선순위 이상의 로그만 기록되도록 필터링할 수 있습니다. 인자가 주어지지 않으면 마스크는 무시됩니다.

예제 코드

아래는 프로그램 이름을 ident로 지정한 뒤 LOG_NOTICE 수준의 로그를 기록하는 간단한 예제입니다.

import syslog, sys

syslog.openlog(sys.argv[0])
syslog.syslog(syslog.LOG_NOTICE, "This is a Log Notice")
syslog.openlog()

실행 결과 확인

스크립트를 실행한 후 /var/log/syslog 파일을 열어보면, 방금 기록한 로그가 시스템 로그에 함께 저장된 것을 확인할 수 있습니다.

$ python3 posix_example.py
$ sudo cat /var/log/syslog
Oct  7 00:05:23 unix_user-VirtualBox anacron[14271]: Job `cron.daily' terminated
Oct  7 00:05:23 unix_user-VirtualBox anacron[14271]: Normal exit (1 job run)
Oct  7 00:17:01 unix_user-VirtualBox CRON[14396]: (root) CMD (   cd / && run-parts --report /etc/cron.hourly)
Oct  7 00:22:35 unix_user-VirtualBox gnome-software[1599]: no app for changed ubuntu-dock@ubuntu.com
Oct  7 00:22:35 unix_user-VirtualBox gnome-software[1599]: no app for changed ubuntu-appindicators@ubuntu.com
Oct  7 00:22:36 unix_user-VirtualBox gnome-shell[1296]: [AppIndicatorSupport-DEBUG] Registering StatusNotifierItem :1.59/org/ayatana/NotificationItem/software_update_available
Oct  7 00:22:37 unix_user-VirtualBox gvfsd-metadata[3664]: g_udev_device_has_property: assertion 'G_UDEV_IS_DEVICE (device)' failed
Oct  7 00:22:37 unix_user-VirtualBox gvfsd-metadata[3664]: g_udev_device_has_property: assertion 'G_UDEV_IS_DEVICE (device)' failed
Oct  7 00:25:47 unix_user-VirtualBox snapd[5511]: storehelpers.go:398: cannot refresh: snap has no updates available: "core", "gnome-3-26-1604", "gnome-calculator", "gnome-characters", "gnome-logs", "gnome-system-monitor", "gtk-common-themes"
Oct  7 00:25:47 unix_user-VirtualBox snapd[5511]: autorefresh.go:387: auto-refresh: all snaps are up-to-date
Oct  7 00:27:32 unix_user-VirtualBox example.py: This is a Log Notice

마지막 줄을 보면 example.py: This is a Log Notice라는 항목이 추가된 것을 알 수 있습니다. 이처럼 openlog()로 지정한 ident가 로그 앞에 붙어, 어떤 프로그램이 남긴 기록인지 한눈에 파악할 수 있습니다.