eunzae's develog

[Python]웹 로그 데이터셋 만들기 본문

Database/Data Engineering

[Python]웹 로그 데이터셋 만들기

eunzae 2021. 12. 17. 21:06

웹 서버의 액세스 로그로 데이터셋을 만들어보았다.

 

1. 웹 서버 액세스 로그 파일 다운로드

회사의 웹 서버 액세스 로그는 보안 상 사용할 수 없어서...

구글링으로 예제 데이터를 구했다.

 

예제데이터: https://www.kaggle.com/eliasdabbas/web-server-access-logs

 

Web Server Access Logs

A sample of web server logs file

www.kaggle.com

로그데이터 예시

2. 코드 작성

import pandas as pd
import re

# 로그를 읽어와서 각 행에 매치하도록 정규식 작성
pattern = re.compile('(^\S+) - - \[(.*)] "(\S+ \S+) \S+" (\S+) (\S+)')

# 데이터 예시: 4.36.149.75 - - [22/Jan/2019:04:04:41 +0330] "GET /product/29585/80570 HTTP/1.1" 200 41478 "-" "Mozilla/5.0 (compatible; AhrefsBot/6.1; +http://ahrefs.com/robot/)" "-"

# 경로 설정
input_log_path = r"/Users/shin-eunjae/Desktop/code/webserver_access_log_parsing/data/access.log"

# 예제데이터 다운로드 주소: https://www.kaggle.com/eliasdabbas/web-server-access-logs

# 정규 표현으로 파싱하는 함수 작성(일치하지 않는 행은 그냥 버린다)
def parse_access_log(path):
    for line in open(path):
        for m in pattern.finditer(line):
            yield m.group(1,2,3,4,5)
            
# 데이터프레임에 변수 보관하기
columns = ['IP', 'time', 'request', 'status', 'bytes']
data = parse_access_log(input_log_path)
df = pd.DataFrame(data, columns=columns)

# 'time'칼럼을 덮어쓴다(타임 존 삭제)
df.time = pd.to_datetime(df.time, format='%d/%b/%Y:%X', exact=False)

# 데이터 확인
df.head()

# csv 파일로 보관
output_log_path = r"/Users/shin-eunjae/Desktop/code/webserver_access_log_parsing/data/"
df.to_csv(output_log_path + 'access_log.csv', index=False)

 

예쁘게 csv파일로 저장이 됐다.

 

 

로그파일 정의: https://httpd.apache.org/docs/2.4/logs.html

 

로그파일 - Apache HTTP Server Version 2.4

로그파일 이 문서는 최신판 번역이 아닙니다. 최근에 변경된 내용은 영어 문서를 참고하세요. 효율적으로 웹서버를 관리하려면 발생하는 문제와 함께 서버의 활동과 성능에 대해 알아야 한다.

httpd.apache.org

 

참고도서: 빅데이터를 지탱하는 기술, 니시다 케이스케