#!/bin/bash
# collect_logs.sh
# 收集并过滤日志

PACKAGE_NAME="${1:-com.example.app}"
DURATION="${2:-30}"
OUTPUT_FILE="logs_${PACKAGE_NAME}_$(date +%Y%m%d_%H%M%S).txt"

echo "Collecting logs for package: $PACKAGE_NAME"
echo "Duration: ${DURATION} seconds"
echo "Output file: $OUTPUT_FILE"
echo "Press Ctrl+C to stop early"
echo ""

# 清空日志缓冲区
adb logcat -c

# 开始收集日志
adb logcat | grep --line-buffered "$PACKAGE_NAME" > "$OUTPUT_FILE" &
LOGCAT_PID=$!

# 等待指定时间
sleep "$DURATION"

# 停止日志收集
kill $LOGCAT_PID 2>/dev/null
wait $LOGCAT_PID 2>/dev/null

# 统计日志行数
LINE_COUNT=$(wc -l < "$OUTPUT_FILE" 2>/dev/null || echo "0")

echo ""
echo "Log collection completed!"
echo "  File: $OUTPUT_FILE"
echo "  Lines: $LINE_COUNT"

# 显示最后几行
if [ "$LINE_COUNT" -gt 0 ]; then
    echo ""
    echo "Last 10 lines:"
    tail -n 10 "$OUTPUT_FILE"
fi
