Linux 튜토리얼: 로그를 CSV에서 JSON으로
발행: (2026년 1월 18일 오후 10:59 GMT+9)
2 min read
원문: Dev.to
Source: Dev.to
설정 디렉터리
mkdir -p tutorial
cd tutorial
샘플 로그 생성
# Generate logs inside the tutorial folder
echo "2026-01-18 05:42:09 | INFO | system initialized" >> myapp.log
echo "2026-01-18 05:42:09 | ERROR | disk space low" >> myapp.log
echo "2026-01-18 05:42:09 | INFO | user logged in" >> myapp.log
파일: myapp.log
2026-01-18 05:42:09 | INFO | system initialized
2026-01-18 05:42:09 | ERROR | disk space low
2026-01-18 05:42:09 | INFO | user logged in
로그를 CSV 로 변환
sed 's/ | /","/g; s/^/"/; s/$/"/' myapp.log > myapp.csv
파일: myapp.csv
"2026-01-18 05:42:09","INFO","system initialized"
"2026-01-18 05:42:09","ERROR","disk space low"
"2026-01-18 05:42:09","INFO","user logged in"
CSV‑to‑JSON 파이썬 스크립트
csv_to_json.py 파일을 만들고 아래 코드를 붙여넣으세요:
import csv
import json
import sys
from pathlib import Path
def convert(csv_file, json_file):
csv_path = Path(csv_file)
json_path = Path(json_file)
if not csv_path.exists():
print(f"Error: Input file '{csv_file}' not found.")
print("Make sure you are running this from the project root and have generated the CSV.")
sys.exit(1)
data = []
with open(csv_path, mode='r', encoding='utf-8') as f:
reader = csv.DictReader(f, fieldnames=["timestamp", "level", "message"])
for row in reader:
data.append(row)
# Ensure parent directory for output exists
json_path.parent.mkdir(parents=True, exist_ok=True)
with open(json_path, mode='w', encoding='utf-8') as f:
json.dump(data, f, indent=4)
print(f"Successfully converted {csv_file} to {json_file}!")
if __name__ == "__main__":
# Find files relative to the script's own directory
script_dir = Path(__file__).parent
csv_file = script_dir / 'myapp.csv'
json_file = script_dir / 'myapp.json'
convert(csv_file, json_file)
변환 실행
python3 csv_to_json.py
파일: myapp.json
[
{
"timestamp": "2026-01-18 05:42:09",
"level": "INFO",
"message": "system initialized"
},
{
"timestamp": "2026-01-18 05:42:09",
"level": "ERROR",
"message": "disk space low"
},
{
"timestamp": "2026-01-18 05:42:09",
"level": "INFO",
"message": "user logged in"
}
]
생성된 JSON 파일은 웹 대시보드, 데이터 분석 도구에서 사용할 수 있으며, 언어 모델 실험을 위한 테스트 및 벤치마크 데이터 생성에도 활용할 수 있습니다.