You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PowerShell提取Apache Tomcat日志指定位置的错误片段

PowerShell脚本实现Tomcat日志指定错误段提取

需求说明

从Tomcat日志中提取最新启动后第一条SEVERE错误到下一条SEVERE错误之前的所有内容,具体规则:

  1. 匹配最后一次出现Server version的行,对应最新一次服务启动位置
  2. 从该位置向后查找第一个SEVERE级别的错误行
  3. 输出该行及后续内容,遇到第二个SEVERE行立即停止且不输出该行

可用实现代码

# 替换为实际日志文件路径
$logFilePath = "X:\full\path\to\logfile.txt"
$allLogLines = Get-Content -Path $logFilePath

# 定位最后一次服务启动的位置
$lastStartupMatch = $allLogLines | Select-String -Pattern 'Server version' | Select-Object -Last 1
if (-not $lastStartupMatch) {
    Write-Warning "未检测到服务启动标记行"
    exit
}
$startSplitIndex = $lastStartupMatch.LineNumber - 1
$logsAfterLastStartup = $allLogLines | Select-Object -Skip $startSplitIndex

# 定位当前启动日志段的SEVERE错误位置
$severeMatchList = $logsAfterLastStartup | Select-String -Pattern 'SEVERE' | Select-Object -First 2
if ($severeMatchList.Count -lt 1) {
    Write-Warning "最新启动后未检测到SEVERE级别错误"
    exit
}

# 截取目标内容
$firstSevereIndex = $severeMatchList[0].LineNumber - 1
if ($severeMatchList.Count -eq 1) {
    $targetContent = $logsAfterLastStartup | Select-Object -Skip $firstSevereIndex
}
else {
    $secondSevereIndex = $severeMatchList[1].LineNumber - 1
    $takeLength = $secondSevereIndex - $firstSevereIndex
    $targetContent = $logsAfterLastStartup | Select-Object -Skip $firstSevereIndex -First $takeLength
}

# 输出结果
$targetContent

原错误代码问题说明

之前尝试的代码错误选取了SEVERE错误的最后一条而非第一条,且未做第二条SEVERE行的截断处理,导致输出内容不符合需求。

内容的提问来源于stack exchange,提问作者Paul H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 21:45:03