[Python] log 파일 분석 및 Markdown 보고서 생성

2025. 4. 20. 00:18

시스템 로그 파일은 운영 과정에서 발생하는 이벤트를 기록하여 장애나 이상 상황을 추적하는 데 매우 유용하다.

이번 포스팅에서는 Python으로 .log 형식의 로그 파일을 분석하고, 사고 원인을 추출하여 Markdown 보고서로 자동 생성하는 방법

포스팅할 예정이다.

 

로그 파일 예시 (space_mission_log_sample.log)

// space_mission_log_sample.log
timestamp,event,message
2024-10-10 09:00:00,INFO,Vehicle boot sequence initialized.
2024-10-10 09:03:00,INFO,Primary systems online. Battery levels nominal.
2024-10-10 09:06:00,INFO,Communications link with base station established.
2024-10-10 09:09:00,INFO,Flight system diagnostics passed.
2024-10-10 09:12:00,INFO,Thrusters check complete. All engines green.
2024-10-10 09:15:00,INFO,Cargo hatch secured.
2024-10-10 09:18:00,INFO,Final launch checklist approved.
2024-10-10 09:21:00,INFO,Countdown initiated.
2024-10-10 09:24:00,INFO,Ignition sequence started.
2024-10-10 09:27:00,INFO,Liftoff successful. Vehicle leaving pad.
2024-10-10 09:30:00,INFO,First stage separation confirmed.
2024-10-10 09:33:00,INFO,Second stage ignition nominal.
2024-10-10 09:36:00,INFO,Payload fairing deployed.
2024-10-10 09:39:00,INFO,Orbital insertion burn initiated.
2024-10-10 09:42:00,INFO,Entered low Earth orbit.
2024-10-10 09:45:00,INFO,Deploying satellite payload.
2024-10-10 09:48:00,INFO,Payload deployment successful.
2024-10-10 09:51:00,INFO,Deorbit burn started for return capsule.
2024-10-10 09:54:00,INFO,Reentry interface reached.
2024-10-10 09:57:00,INFO,Heat shield nominal during descent.
2024-10-10 10:00:00,INFO,Main parachutes deployed.
2024-10-10 10:03:00,INFO,Landing confirmed. Recovery initiated.
2024-10-10 10:05:00,INFO,Post-landing system check underway.
2024-10-10 10:07:00,INFO,Oxygen valve showing abnormal pressure.
2024-10-10 10:10:00,INFO,Oxygen system unstable.
2024-10-10 10:13:00,INFO,Containment breach in oxygen tank detected.
2024-10-10 10:15:00,INFO,Minor explosion in oxygen storage compartment.
2024-10-10 10:20:00,INFO,Systems powered down for safety protocol.

 

 

 

 

  • timestamp: 로그 발생 시각
  • event: 이벤트 레벨 (여기선 모두 INFO)
  • message: 이벤트 메시지

 

분석 목표

  • 로그에서 산소 시스템 관련 이벤트를 필터링
  • "explosion"과 같은 단어를 기반으로 사고 원인을 추출
  • Markdown 형식으로 보고서 작성
def analyze_log_and_generate_report(log_file, md_file):
    log_data = []

    # 1. 로그 파일 열기 및 데이터 수집
    with open(log_file, 'r', encoding='utf-8') as log:
        next(log)  # 첫 줄 헤더 건너뛰기
        for line in log:
            parts = line.strip().split(',')
            log_data.append({
                'timestamp': parts[0],
                'event': parts[1],
                'message': parts[2]
            })

    # 2. 사고 원인 추출
    incident_logs = [entry for entry in log_data if 'Oxygen' in entry['message']]
    cause = ""
    for entry in incident_logs:
        if 'explosion' in entry['message'].lower():
            cause = entry['message']
            break
    if not cause and incident_logs:
        cause = incident_logs[-1]['message']  # 가장 마지막 산소 관련 메시지 사용

    # 3. Markdown 보고서 작성
    markdown_content = f"사고 원인: {cause}\n\n"
    for entry in reversed(log_data):
        markdown_content += f"- {entry['timestamp']} - {entry['event']}: {entry['message']}\n"

    # 4. 파일로 저장
    with open(md_file, 'w', encoding='utf-8') as f:
        f.write(markdown_content)

    print(f\"보고서가 '{md_file}'에 저장되었습니다.\")

 

 

 

 

생성된 Markdown 보고서 예시

사고 원인: Minor explosion in oxygen storage compartment.

- 2024-10-10 10:20:00 - INFO: Systems powered down for safety protocol.
- 2024-10-10 10:15:00 - INFO: Minor explosion in oxygen storage compartment.
- 2024-10-10 10:13:00 - INFO: Containment breach in oxygen tank detected.
- 2024-10-10 10:10:00 - INFO: Oxygen system unstable.
- 2024-10-10 10:07:00 - INFO: Oxygen valve showing abnormal pressure.
...
728x90

'Study > Python' 카테고리의 다른 글

[Python] 클래스  (1) 2025.03.28
[Python] 변수와 상수  (0) 2022.08.02

BELATED ARTICLES

more