Search and download Azure Function Application Logs from PowerShell

Draft

If you're interested in details, ping me @dicshaunary on Twitter. Or read the Azure KUDU REST documentation.

The following script (which may be missing important details - let me know) downloads the most recent Azure Function Application Log file that contains a search term.

# Find your login credentails at
# portal.azure.com > Some App Service > Deployment Credentials

$username = ""
$password = ""

$appServiceName = ""
$functionName = ""
$searchTerm = ""

# build the auth header

$base64AuthInfo = 
    [Convert]::ToBase64String(
        [Text.Encoding]::ASCII.GetBytes(
            ("{0}:{1}" -f $env:username, $password)));

$authHeaders = @{Authorization=("Basic {0}" -f $base64AuthInfo)} 

# build the REST URI

$kuduUri = "https://$($appServiceName).scm.azurewebsites.net/"
$vfsApi = "api/vfs/"
$functionLogFilesPath = "LogFiles/Application/Functions/Function/"
$logFileDirectory = 
    ($kuduUri + $vfsApi + $functionLogFilesPath + $functionName);

# download log file names and order recency

$response = Invoke-WebRequest -Uri $logFileDirectory `
    -Method GET `
    -Headers $authHeaders

$logFiles = ($response.Content | ConvertFrom-Json) | `
    Sort-Object -Descending { [DateTime]::Parse($_.crtime) }  

# prepare the save the log file locally

$targetLogFileSavePath;
New-Item -ItemType Directory $functionLogFilesPath -Force;

# find target log file

$targetLogFileSavePath;
$targetLogFileContent = $logFiles |
    ForEach-Object {  
        $fileUri = ($logFileDirectory + $_.name)
        $targetLogFileSavePath = ($functionLogFilesPath + $_.name)

        Write-Host "Downloading $($fileUri)"
        $response = Invoke-WebRequest `
            -Uri $fileUri `
            -Method GET -Headers $authHeaders 
        $index = $response.RawContent.IndexOf("`r`n`r`n");
        $logContent = $response.RawContent.SubString($index);
        Add-Content -Path $targetLogFileSavePath -Value $logContent

        $response
    } | 
    Where-Object {
        $_.RawContent -match $env:searchTerm
    } |
    Select-Object -first 1;

if ($targetLogFileContent -eq $null) {  
    Write-Host
    Write-Host "Log file not found containing $($env:searchTerm)."
    Write-Host "Make sure Application Loggging (Filesystem) is enabled."
    Write-Host
}
else {  
    Write-Host
    Write-Host "Open $($targetLogFileSavePath) to view the log."
    Write-Host
}

# Enable Azure Application Logging (Filesystem):
# 1. portal.azure.com
# 2. App Service Settings (for some application)
# 3. Diagnostic logs 
# 4. Application Logging (Filesystem) > ON
# 5. Level > Information
# 6. Save