本文目录导读:

获取内存错误信息通常需要结合操作系统和编程语言的特性,以下是几种常见场景的脚本方法:
Linux系统 - 使用Shell脚本
查看系统内存错误日志
#!/bin/bash # 查看dmesg中的内存错误 dmesg | grep -i "memory" | grep -i "error\|fail\|warn" # 查看系统日志中的内存错误 journalctl -k | grep -i "memory" | grep -i "error\|fail\|warn" # 查看EDAC(错误检测和纠正)报告 cat /sys/devices/system/edac/mc/mc*/csrow*/ch*_ce_count 2>/dev/null cat /sys/devices/system/edac/mc/mc*/csrow*/ch*_ue_count 2>/dev/null
Windows系统 - 使用PowerShell
获取Windows内存诊断结果
# 检查Windows内存诊断工具结果
Get-WinEvent -LogName System | Where-Object {
$_.Id -eq 1101 -or $_.Id -eq 1102 -or $_.Id -eq 1103
} | Format-List
# 查看内存相关的应用程序错误
Get-WinEvent -LogName Application | Where-Object {
$_.LevelDisplayName -match "Error" -and
$_.ProviderName -match "Memory|Hardware"
} | Select-Object TimeCreated, Id, ProviderName, Message
Python脚本获取进程内存错误
import psutil
import traceback
import sys
def get_memory_errors():
"""获取当前进程的内存使用异常"""
try:
process = psutil.Process()
mem_info = process.memory_info()
# 检查内存使用是否异常
if mem_info.rss > 1024 * 1024 * 1000: # 超过1GB
return f"High memory usage: {mem_info.rss / 1024 / 1024:.2f} MB"
# 检查内存泄漏迹象
if mem_info.vms > mem_info.rss * 10: # 虚拟内存远大于物理内存
return f"Possible memory leak: vms={mem_info.vms}, rss={mem_info.rss}"
except Exception as e:
return f"Error checking memory: {str(e)}"
return None
# 捕获内存错误异常
def safe_memory_operation():
try:
# 模拟可能的内存错误
large_list = [0] * 10**8 # 可能导致MemoryError
except MemoryError as e:
traceback.print_exc()
return f"Memory Error: {str(e)}"
except Exception as e:
return f"General Error: {str(e)}"
if __name__ == "__main__":
result = get_memory_errors()
if result:
print(f"Memory alert: {result}")
跨平台 - Node.js脚本
const os = require('os');
const fs = require('fs');
// 获取系统内存信息
function getMemoryErrors() {
const totalMem = os.totalmem();
const freeMem = os.freemem();
const usagePercent = ((totalMem - freeMem) / totalMem) * 100;
console.log(`Total Memory: ${(totalMem / 1024 / 1024).toFixed(2)} MB`);
console.log(`Free Memory: ${(freeMem / 1024 / 1024).toFixed(2)} MB`);
console.log(`Memory Usage: ${usagePercent.toFixed(2)}%`);
// 检查内存不足警告
if (usagePercent > 90) {
console.warn('WARNING: Memory usage exceeds 90%');
}
// 读取Windows事件日志(需要管理员权限)
if (process.platform === 'win32') {
try {
const log = fs.readFileSync('C:\\Windows\\System32\\winevt\\Logs\\System.evtx');
// 解析逻辑...
} catch (e) {
console.log('Cannot access Windows Event Log');
}
}
}
// 捕获未处理的异常
process.on('uncaughtException', (error) => {
if (error.code === 'ERR_OUT_OF_MEMORY') {
console.error('OUT OF MEMORY ERROR:', error.message);
process.exit(1);
}
});
自动化监控脚本(Bash)
#!/bin/bash
# 持续监控内存错误
while true; do
# 检查内存使用率
MEM_USAGE=$(free -m | awk 'NR==2{printf "%.2f", $3*100/$2}')
# 检查系统日志中的内存错误
if dmesg | grep -q "Out of memory\|oom-killer\|Memory failure"; then
echo "$(date): Memory error detected"
dmesg | tail -n 20 >> /var/log/memory_errors.log
fi
# 高内存使用告警
if (( $(echo "$MEM_USAGE > 90" | bc -l) )); then
echo "$(date): High memory usage: ${MEM_USAGE}%"
ps aux | sort -nrk 4 | head -5 >> /var/log/memory_usage.log
fi
sleep 60
done
使用建议
- 权限问题:部分操作需要管理员/root权限
- 日志轮转:长时间运行记得清理旧日志
- 性能影响:监控脚本不要过于频繁运行
- 错误分级:区分严重错误和警告信息
选择适合你的操作系统和编程环境的方案,根据具体需求调整监控参数和告警阈值。