정규 표현식을 이용해 아파치로그 파싱하기

Heejeong Choi·2021년 10월 10일
0

Trials & Errors

목록 보기
3/4
post-thumbnail

학원 수료 이전에 패스를 해야하는 과정이 있다. 그 때 당시에 나는 구구단이나 짜고 데이터구조나 배우고 있을 무렵이었다😢 아파치 로그.txt를 받았을 때에는 정말 !!!ㄴㅇㄱ!!! 이 자체 그대로였다. 진짜 거짓말안하고 로그는 10000개 정도? 거기서 이제 사용자의 정보를 필요에 따라 추출해오는 것이 바로 과제였음🙂 사실 처음에 문제 파악하는데만 하루가 걸렸다고 합니다... 백엔드 개발자라면!! 혹은 웹 서비스를 운영하는 서버 관리자라면 외부에서 어떤 요청이 들어오는지 그리고 어떤 사용자가 있는지에 대한 정보를 담고 있는 액세스 로그에 관심을 가질 필요가 있습니다. 고로 우리는 아파치로그를 공부를 해보아야 합니다🤗

그래서 아파치 로그가 뭔가여...?😢

Apache 로그는 다른 컴퓨터의 요청, Apache에서 보낸 응답 및 Apache 서버 내부 작업을 포함하여 Apache 웹 서버에서 처리한 이벤트를 기록합니다. 이 절에서는 Apache에서 생성된 로그 유형, 로그가 저장된 위치 및 로그 해석 방법을 포함하여 Apache 로깅의 기본 사항에 대해 설명합니다.

위 그림에서 보이는 것 처럼, 아파치 로그는 7가지로 다음과 같이 분할 할 수 있습니다.

  1. 원격 호스트 IP 주소(요청자)
  2. 요청 시간
  3. 'GET' 메서드를 사용하고 '/api/aaaa'라는 경로에 'HTTP/1.1'의 프로토콜로 요청
  4. HTTP 상태 코드
  5. HTTP 헤더를 제외한 전송 바이트 수
  6. 요청을 처리하는 데 걸린 시간(ms)
  7. 리퍼러(referrer)

🔥 과제를 한번 해보자

우선, 과제의 조건이 어떻게 되는지 다시한번 봅시다🙋🏽‍♀️

  • 주어진 아파치 로그의 텍스트 파일을 읽고, csv 파일로 변환하기
  • 로그 항목별로 주어진 문항에 따라 값 구하기
class Parsing {

//text file 읽어오기 
    public static String readFile(String fileName) {
        StringBuilder string = new StringBuilder();
        FileReader f = null;
        char[] buff = new char[1024];

        try {
            f = new FileReader(fileName);
            while (f.read(buff) != -1) {
                string.append(buff);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                f.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return string.toString();
    }

//읽어온 파일 파싱하기
    public static void main(String[] args) throws IOException {
        String apache = readFile("/apache_logs.txt");

        /* File file = new File("/user-agent.csv");
        FileOutputStream fos = new FileOutputStream(file);
        PrintStream ps = new PrintStream(fos);
        System.setOut(ps); */

        String regexIp = "(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})";
        String regexUserIdent = "(\\s-\\s-\\s)";
        String regexDate = "(\\[\\d{2}\\/\\w{3}\\/\\d{4}:\\d{2}:\\d{2}:\\d{2}\\s\\+\\d{4}\\])";
        String regexUri = "(\\s\\\"(GET|POST|OPTIONS|HEAD)\\s\\/(\\??\\s?|\\??\\w.+)HTTP\\/\\d\\.\\d\\\")";
        String regexResponse = "(\\s(\\d{3}|-))";
        String regexDataAmount = "(\\s(\\d*|-))";
        String regexUserURL = "(\\s(\\\"(-|(http|https):\\/\\/(\\w+:{0,1}\\w*@)?(\\S+)(:\\d+)?(\\/|\\/([\\w#!:.?+=&%@!\\-\\/]))?)\\\"))";
        String regexUserOS = "(\\s\\\"(.+))";
        String regexUserAgent = "(\\\\s\\\".+?[/\\\\s][\\\\d.]+)";

        Pattern pattern = Pattern.compile(regexIp+regexUserIdent+regexDate+regexUri+regexResponse+regexDataAmount+regexUserURL+regexUserOS);
        Pattern userAgent = Pattern.compile(regexUserAgent);
        Matcher matcher = pattern.matcher(apache);
        Matcher matcher2 = userAgent.matcher(apache);

        while (matcher.find()) {
            ArrayList<String> log = new ArrayList<>(1);
            log.add(matcher.group(1));
            log.add(matcher.group(2));
            log.add(matcher.group(3));
            log.add(matcher.group(4));
            log.add(matcher.group(7));
            log.add(matcher.group(9));
            log.add(matcher.group(11));
            log.add(matcher.group(20));

            System.out.println(log);

            ArrayList<String> user_agent = new ArrayList<>(1);
            user_agent.add(matcher2.group(1));
            System.out.println(userAgent);
        }

        // System.out.print(String.format("%s\t,%s\t,%s\t,%s\t,%s\t,%s\t,%s\t,%s\n", matcher.group(1), matcher.group(2), matcher.group(3), matcher.group(4), matcher.group(7), matcher.group(9), matcher.group(11), matcher.group(20)));
        /* }
        float percentage = (i/size)*100;
        System.out.println(percentage + "%"); */
    }
}

내 서버에는 누가 들어오는 걸까 - Apache 액세스 로그를 Elastic Stack으로 분석하기
Ultimate Guide to Logging
Apache HTTP Server Version 2.4

profile
Welcome to my velog! I love learning something new to build up my ability in development field. I don't think it is shame not to know, but it is shame to pretend to know about something you don't know.

0개의 댓글