GC Full GC 日志處理

#!/bin/bash

SMS_URL="${SMS_URL}"
SMS_USERNAME="${SMS_USERNAME}"
SMS_PASSWORD="${SMS_PASSWORD}"

CURL_REQUEST_TYPE="POST"
CURL_CONTENT_TYPE="application/x-www-form-urlencoded"

function send_sms_msg {
    local username="$1"
    local password="$2"
    local url="$3"
    local message="$4"
    for mobile in 13512250001 13512250002
    do
        response=$(curl --silent --show-error --insecure --request "$CURL_REQUEST_TYPE" --url "$url" --header "Content-Type: $CURL_CONTENT_TYPE" --data "user=$username&&password=$password&&mobile=$mobile&&message=$message")
        if [ $? -ne 0 ]; then
            echo "SMS sending failed for mobile number $mobile" >&2
            continue
        fi
    done
}

function parse_gc_log {
    local log_file="$1"
    if [ ! -s "$log_file" ]; then
        echo "Error: GC log file '$log_file' does not exist or is empty."
        exit 1
    fi
    # GC日志分析邏輯  處理日志中最后一條匹配的Full GC日志
    # 2024-06-04T16:07:12.842+0800: 10880.297: [Full GC (System.gc()) [PSYoungGen: 12012K->0K(3124736K)] [ParOldGen: 7508702K->7514905K(23068672K)] 7520714K->7514905K(26193408K), [Metaspace: 121827K->121817K(1161216K)], 9.6254819 secs] [Times: user=34.85 sys=0.00, real=9.62 secs] 
    #
    old_gen_info=$(awk '/Full GC/ {last_match=$0;last_index=ARGIND} END {
        if (last_index==ARGIND) {
            match(last_match,/([0-9]+?-[0-9]+?-[0-9]+?T[0-9]+?:[0-9]+?:[0-9]+?).*ParOldGen: ([0-9]+?)K->([0-9]+?)K\(([0-9]+?)K\)/, gc_info);
            if (gc_info[1]) {
                old_gen_record_time=gc_info[1];
                old_gen_used_kbytes=gc_info[3];
                old_gen_total_kbytes=gc_info[4];
                percentage=(old_gen_used_kbytes/old_gen_total_kbytes)*100;
                printf "%s %d %d %2.0f\n",old_gen_record_time, old_gen_used_kbytes, old_gen_total_kbytes, percentage;
            }
        }
    }' "$log_file")
    if [[ -z "$old_gen_info" ]]; then
        echo "Error: Failed to parse GC log or no valid Full GC record found."
        exit 1
    fi
    echo "$old_gen_info"
}

function check_old_gen_usage {
    local log_file="$1"
    local old_gen_info=$(parse_gc_log "$log_file")
    read old_gen_record_time old_gen_used_kbytes old_gen_total_kbytes percentage <<< $old_gen_info
    
    if (( percentage > $threshold && old_gen_total_kbytes != 0 )); then
        alert_msg="${old_gen_record_time}: ${old_gen_used_kbytes}K->${old_gen_total_kbytes}K(${percentage}%)"
        echo "$alert_msg"
        send_sms_msg "$SMS_USERNAME" "$SMS_PASSWORD" "$SMS_URL" "$alert_msg"
    fi
}

# 定義日志文件路徑和閾值
gc_log="/logs/gc.log"
threshold=20
check_old_gen_usage "$gc_log"
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容