首页 > 解决方案 > 我们如何阅读 Azure DevOps 任务日志?

问题描述

我在 azure 管道中有一项任务,该任务执行一些动态测试,但是由于测试数量众多,因此单个测试是否通过或失败,这取决于日志中的内容。

因此,Azure DevOps 步骤始终变为绿色。我希望通过阅读该日志来解决问题,然后根据日志是否包含故障来决定下一步该做什么。因此,假设任务变为绿色并且日志检测到失败,我将决定不发布工件。

如何通过在下一个任务中使用标准 azure api 读取上一个任务的日志然后做出决定,以标准方式解决这个问题?

说明:根据需要

这些测试不是单元,它们实际上是一些自定义的 java 测试,它们是通过.sh从 linux 机器上的自托管代理调用文件来触发的。

标签: azure-devopsazure-pipelinesazure-devops-rest-api

解决方案


如果您无法使用标准错误使管道失败,您可以使用Builds - Get Build Log来调查任务并根据结果设置一个变量,在其他任务中,使用此变量的自定义条件,或者只是使所有管道失败。

所以,一个类似这样的 PowerShell 脚本:

$token = "YOUR-PAT"
Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))
 
# Construct the REST URL to obtain Build ID
$uri = "$(System.TeamFoundationCollectionUri)/$(System.TeamProject)/_apis/build/builds/logs/{logId}?api-version=5.1"
 
# Invoke the REST call and capture the results
$log= Invoke-RestMethod -Uri $uri -Method Get -ContentType "application/json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}

if($log -match "some error")
{
    # Option 1: set a variable
    Write-Host "##vso[task.setvariable variable=testsStatus]failed"
    # Now in the artifacts task use custom condition:
    # and(succeeded(), ne(variables['testsStatus'], 'failed'))

    # Option 1: fail the pipeline
    Write-Error "The tests not passed!"
}

(您可以使用 API Builds - Get Build Logs 获取日志 ID )


推荐阅读