Health Response Format
Demonstrates configuring health endpoints with Auto response format for content negotiation with multiple diverse health probes for comprehensive monitoring.
Full source
File: pwsh/tutorial/examples/16.7-Health-Response-Format.ps1
<#
Sample: Health Response Format
Purpose: Shows how to configure the health endpoint to return YAML, XML, or JSON responses.
File: 16.7-Health-Response-Format.ps1
Notes: Demonstrates ResponseContentType parameter options with multiple probes.
#>
param(
[int]$Port = 5000,
[IPAddress]$IPAddress = [IPAddress]::Loopback
)
## 1. Logging
New-KrLogger | Add-KrSinkConsole | Register-KrLogger -Name 'console' -SetAsDefault
## 2. Server
New-KrServer -Name 'Health Response Format Demo'
## 3. Listener (port 5000)
Add-KrEndpoint -Port $Port -IPAddress $IPAddress
#
## 5. Add some diverse probes for demonstration
Add-KrHealthProbe -Name 'Database' -Tags 'core', 'data' -ScriptBlock {
# Simulate database connectivity check
$connectionTime = Get-Random -Minimum 10 -Maximum 50
$data = @{ connectionTimeMs = $connectionTime; server = 'localhost:5432' }
New-KrProbeResult 'Healthy' "Connected in ${connectionTime}ms" -Data $data
}
Add-KrHealthProbe -Name 'Cache' -Tags 'core', 'perf' -ScriptBlock {
# Simulate cache health check
$hitRatio = [math]::Round((Get-Random -Minimum 85 -Maximum 98) / 100.0, 2)
$data = @{ hitRatio = $hitRatio; entries = 1247 }
$status = if ($hitRatio -lt 0.8) { 'Degraded' } else { 'Healthy' }
New-KrProbeResult $status "Hit ratio: $($hitRatio * 100)%" -Data $data
}
Add-KrHealthProbe -Name 'Disk Space' -Tags 'infra' -ScriptBlock {
# Simulate disk space check
$freePercent = Get-Random -Minimum 25 -Maximum 85
$status = if ($freePercent -lt 10) { 'Unhealthy' } elseif ($freePercent -lt 20) { 'Degraded' } else { 'Healthy' }
$data = @{ freePercent = $freePercent; totalGB = 500; freeGB = [math]::Round($freePercent * 5, 1) }
New-KrProbeResult $status "Free space: $freePercent%" -Data $data
}
## 6. Enable configuration
#Enable-KrConfiguration
## 7. Health endpoint with different response formats (uncomment one at a time to test)
# JSON (default)
Add-KrHealthEndpoint -Pattern '/healthz' -DefaultTags 'core' -ResponseContentType Auto
Enable-KrConfiguration
## 8. Start server
Start-KrServer
Step-by-step
- Register a health endpoint with
-ResponseContentType Autofor content negotiation. - Add diverse probes (database/cache/disk) with realistic thresholds.
- Optionally set
-XmlRootElementNameand-Compressfor XML. - Start the server and call the endpoint with different Accept headers.
Response Formats
YAML Format
Human-readable format ideal for debugging and configuration review:
overallStatus: Healthy
totalDuration: "00:00:00.1234567"
probes:
- name: "Database"
status: "Healthy"
description: "Connected in 23ms"
JSON Format
Standard API format for programmatic consumption:
{
"overallStatus": "Healthy",
"totalDuration": "00:00:00.1234567",
"probes": [
{
"name": "Database",
"status": "Healthy",
"description": "Connected in 23ms"
}
]
}
XML Format
Legacy enterprise integration format:
<HealthReport>
<OverallStatus>Healthy</OverallStatus>
<TotalDuration>00:00:00.1234567</TotalDuration>
<Probes>
<ProbeResult>
<Name>Database</Name>
<Status>Healthy</Status>
<Description>Connected in 23ms</Description>
</ProbeResult>
</Probes>
</HealthReport>
Probe Examples
This sample includes three diverse probes demonstrating different monitoring scenarios:
Database Probe
Simulates database connectivity with realistic connection timing:
- Healthy: Connection established with timing metrics
- Data: Connection time in milliseconds, server endpoint
Cache Probe
Monitors cache performance with hit ratio tracking:
- Healthy: Hit ratio ≥ 80%
- Degraded: Hit ratio < 80%
- Data: Hit ratio percentage, cache entry count
Disk Space Probe
Checks available disk space with tiered alerting:
- Healthy: Free space ≥ 20%
- Degraded: Free space 10-19%
- Unhealthy: Free space < 10%
- Data: Free percentage, total GB, available GB
Try It
Start the script, then test the endpoint with different Accept headers:
# JSON format (default)
Invoke-RestMethod http://127.0.0.1:5000/healthz | ConvertTo-Json -Depth 4
# YAML format (with Accept header)
Invoke-RestMethod http://127.0.0.1:5000/healthz -Headers @{'Accept' = 'application/yaml'}
# XML format (with Accept header)
Invoke-RestMethod http://127.0.0.1:5000/healthz -Headers @{'Accept' = 'application/xml'}
# Custom XML root + compact output
Add-KrHealthEndpoint -ResponseContentType Xml -XmlRootElementName 'HealthReport' -Compress
Invoke-RestMethod http://127.0.0.1:5000/healthz -Headers @{'Accept' = 'application/xml'}
# Filter by tags
Invoke-RestMethod 'http://127.0.0.1:5000/healthz?tag=core'
Invoke-RestMethod 'http://127.0.0.1:5000/healthz?tag=infra'
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| Always returns JSON | Missing Accept header | Add -Headers @{'Accept' = 'application/yaml'} to request |
| XML not parsing correctly | Client expecting JSON | Ensure Accept header is set to application/xml |
| Need custom XML root | Using default root Response | Supply -XmlRootElementName 'MyRoot' |
| Need smaller payload | Human-readable indentation default | Use -Compress |
| Probes missing from output | Tag filtering active | Check query string parameters or adjust DefaultTags |
| Content negotiation not working | Wrong ResponseContentType | Ensure -ResponseContentType Auto is used |
References
Previous / Next
Previous: Disk Probe Next: None