본문 바로가기
C.W.K.
Stream
Lesson 05 of 12 · published

로그 파싱

~12 min · logs, parsing, named-groups

Level 0패턴 호기심
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

형식이 일정한 줄은 정규식에 잘 맞아

로그의 각 줄이 같은 형식을 따른다면 이름 붙은 캡처 그룹으로 필요한 필드를 뽑기 좋아. 먼저 실제 로그 샘플을 모으고 형식마다 패턴을 따로 정의해.

Apache와 nginx의 Combined Log Format

192.168.1.1 - - [04/May/2026:14:32:11 +0000] "GET /api/data HTTP/1.1" 200 1234

이 예시에서는 다음처럼 IP, 날짜, 요청 메서드, 경로, 상태 코드, 전송량을 캡처할 수 있어.

(?P<ip>[\d.]+) - - \[(?P<date>[^\]]+)\] "(?P<method>\w+) (?P<path>[^ ]+) [^"]+" (?P<status>\d+) (?P<bytes>\d+)

애플리케이션 로그

2026-05-04T14:32:11Z [INFO] Server started on port 8000처럼 형식이 정해진 줄은 다음 패턴으로 나눌 수 있어.

(?P<timestamp>\S+)\s+\[(?P<level>\w+)\]\s+(?P<message>.+)

긴 패턴은 VERBOSE 모드로 펼쳐

로그 패턴은 필드가 늘수록 빠르게 길어져. VERBOSE 모드와 이름 붙은 그룹을 함께 쓰면 구획과 뜻을 눈으로 확인하기 쉬워.

LOG = re.compile(r'''
    (?P<timestamp>\d{4}-\d{2}-\d{2}T[\d:.]+Z?)
    \s+\[(?P<level>\w+)\]
    \s+(?P<module>[\w.]+)
    \s+(?P<message>.+)
''', re.VERBOSE)

큰 파일은 한 줄씩 처리해

로그 전체를 메모리에 올리지 말고 파일을 순회하며 각 줄에 패턴을 적용해.

with open('big.log') as f:
    for line in f:
        m = LOG.match(line)
        if m:
            handle(m.groupdict())

이 방식은 파일 크기와 무관하게 메모리 사용량을 일정하게 유지해. 처리 속도가 중요하다면 실제 로그와 작업량으로 측정해.

Code

로그 파싱 패턴·python
import re

# Apache/nginx Combined Log Format
APACHE = re.compile(r'''
    (?P<ip>[\d.]+)
    \s+-\s+-\s+
    \[(?P<date>[^\]]+)\]
    \s+"(?P<method>\w+)\s+(?P<path>[^ ]+)\s+[^"]+"
    \s+(?P<status>\d+)
    \s+(?P<bytes>\d+)
''', re.VERBOSE)

line = '192.168.1.1 - - [04/May/2026:14:32:11 +0000] "GET /api/data HTTP/1.1" 200 1234'
m = APACHE.match(line)
print(m.groupdict())

# 앱 로그
APP = re.compile(r'''
    (?P<ts>\d{4}-\d{2}-\d{2}T[\d:.]+Z?)
    \s+\[(?P<level>\w+)\]
    \s+(?P<msg>.+)
''', re.VERBOSE)

m = APP.match('2026-05-04T14:32:11Z [INFO] Server started on port 8000')
print(m.groupdict())
# {'ts': '2026-05-04T14:32:11Z', 'level': 'INFO', 'msg': 'Server started on port 8000'}

# 큰 로그 스트림 처리
def tail_errors(path):
    with open(path) as f:
        for line in f:
            m = APP.match(line)
            if m and m.group('level') == 'ERROR':
                print(m.group('msg'))

External links

Exercise

사용 중인 시스템의 로그 파일 하나를 골라 각 줄에서 타임스탬프, 로그 단계, 메시지를 추출하는 패턴을 작성해. 실제 파일을 한 줄씩 읽으며 적용하고 처음 열 개의 ERROR 항목을 출력해 봐.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.