Loading...
Vietnam Geography App
Loading...
Vietnam Geography App
Khai phá dữ liệu từ file! Học cách đọc, ghi, phân tích và tạo báo cáo từ file văn bản, CSV, log... Mở rộng khả năng tự động hóa và xử lý dữ liệu chuyên nghiệp với Python.
Phân tích log files và tạo báo cáo
import os
from datetime import datetime
from collections import Counter
def create_sample_log():
"""Tạo file log mẫu để test"""
log_entries = [
"2024-01-15 10:30:15 INFO User login: user123",
"2024-01-15 10:31:22 ERROR Database connection failed",
"2024-01-15 10:32:10 INFO User logout: user123",
"2024-01-15 10:35:45 WARNING Low disk space",
"2024-01-15 10:40:12 ERROR File not found: config.txt",
"2024-01-15 10:42:33 INFO User login: user456",
"2024-01-15 10:45:18 ERROR Network timeout"
]
with open('sample.log', 'w', encoding='utf-8') as f:
for entry in log_entries:
f.write(entry + '\n')
print("Đã tạo file sample.log")
def analyze_log(filename):
"""Phân tích log file"""
if not os.path.exists(filename):
print(f"File {filename} không tồn tại!")
return
log_levels = Counter()
error_messages = []
user_activities = []
try:
with open(filename, 'r', encoding='utf-8') as f:
for line_num, line in enumerate(f, 1):
line = line.strip()
if not line:
continue
parts = line.split(' ', 3)
if len(parts) >= 3:
date_str = parts[0]
time_str = parts[1]
level = parts[2]
message = parts[3] if len(parts) > 3 else ""
log_levels[level] += 1
if level == "ERROR":
error_messages.append(f"Line {line_num}: {message}")
if "User" in message:
user_activities.append(f"{date_str} {time_str}: {message}")
# Tạo báo cáo
create_report(log_levels, error_messages, user_activities)
except Exception as e:
print(f"Lỗi đọc file: {e}")
def create_report(log_levels, errors, activities):
"""Tạo báo cáo phân tích"""
report_filename = f"log_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
with open(report_filename, 'w', encoding='utf-8') as f:
f.write("=== BÁO CÁO PHÂN TÍCH LOG ===\n")
f.write(f"Thời gian tạo: {datetime.now()}\n\n")
f.write("1. THỐNG KÊ LOG LEVELS:\n")
for level, count in log_levels.most_common():
f.write(f" {level}: {count}\n")
f.write(f"\n2. ERRORS ĐƯỢC TÌM THẤY ({len(errors)}):\n")
for error in errors:
f.write(f" {error}\n")
f.write(f"\n3. HOẠT ĐỘNG USER ({len(activities)}):\n")
for activity in activities:
f.write(f" {activity}\n")
print(f"Đã tạo báo cáo: {report_filename}")
# Main program
print("=== LOG ANALYZER ===")
print("1. Tạo file log mẫu")
print("2. Phân tích log file")
choice = input("Chọn: ")
if choice == "1":
create_sample_log()
elif choice == "2":
filename = input("Tên file log: ")
analyze_log(filename)
Data processing từ CSV/Excel
Configuration file management
Log analysis và monitoring
Backup và restore systems
Report generation
Data migration tools