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

대부분 로그가 줄 지향, 모양 안정

그게 정확히 정규식의 sweet spot. 각 줄이 같은 템플릿 따름; named 캡처 그룹이 필드 추출.

Apache/nginx Combined Log Format

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

패턴:

(?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 모드 + named 그룹이 maintainable 만듦:

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())

re.compile 결합으로 multi-gigabyte 로그에도 빠름.

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

본인 시스템의 진짜 로그 파일 (Mac 면 ~/Library/Logs, Linux 면 /var/log). 각 줄에서 timestamp, level, message 추출하는 정규식 작성. 파일에 돌려서 첫 10 ERROR 레벨 엔트리 print.

Progress

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

댓글 0

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

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