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

Jenkins控制台日志写入文件时间歇性截断问题求助

Jenkins大日志写入文件间歇性截断问题解决

问题背景

使用以下Groovy代码获取Jenkins构建完整日志并写入文件时,3MB左右的日志会间歇性被截断为1.2-1.5MB,小于1MB的日志无此问题,Jenkins版本2.361.1:

ByteArrayOutputStream stream = new ByteArrayOutputStream()

currentBuild.rawBuild.getLogText().writeLogTo(0, stream)
writeFile file: "archive/${jobName}-log.txt", text: stream.toString()

可能原因

  • 一次性将大日志加载到ByteArrayOutputStream再转成字符串,会在内存中生成大对象,触发Jenkins脚本的内存限制,导致截断
  • writeLogTo方法在写入大流量时,可能存在缓冲区未完全刷新的情况
  • writeFile处理超大字符串时的潜在限制

解决方案

1. 分批次读取写入日志

避免一次性加载全部日志到内存,分块读取并追加到文件:

def logFilePath = "archive/${jobName}-log.txt"
def logText = currentBuild.rawBuild.getLogText()
def totalLines = logText.numberOfLines
def batchSize = 1000
def currentLine = 0

new File(logFilePath).withWriter { writer ->
    while (currentLine < totalLines) {
        def endLine = Math.min(currentLine + batchSize, totalLines)
        def logBatch = logText.getLines(currentLine, endLine)
        writer.write(logBatch.join('\n') + '\n')
        currentLine = endLine
    }
}

2. 直接用文件输出流对接日志输出

跳过ByteArrayOutputStream中转,直接将日志写入文件流,减少内存占用:

def logFilePath = "archive/${jobName}-log.txt"
new FileOutputStream(logFilePath).withStream { out ->
    currentBuild.rawBuild.getLogText().writeLogTo(0, out)
}

3. 调整Jenkins脚本内存限制

如果上述方法仍有问题,可尝试增大Jenkins Groovy脚本的堆内存分配:

  • 进入Jenkins全局配置,找到“Script Console”或“Groovy Script”相关设置
  • 调整脚本引擎的JVM参数(如-Xmx),增大可用内存

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:20:20