終於到 如何為 ASP.NET Core 與相依服務建立執行狀態檢查 系列文章最後一篇:自訂 Health Checks 監控 Shared folder 狀態。 若讀者有閱讀原始碼: AspNetCore.Diagnostics.HealthChecks(GitHub) 或微軟文件:ASP.NET Core 中的健康狀態檢查,應該會發現 HealthChecks 提供非常多的套件讓你監控多種服務運作狀態。但偶有些想要監控的服務沒有套件支援,那該怎麼辦呢 ? 在這一篇文章我們會給簡單的範例,說明如何自訂方法來監控分享資料夾 (Shared folder) 是否可用。


本篇文章範例位置:HealthCheckDemo ,若覺得講解內容過於陌生,建議從第一篇開始閱讀





首先我們會在專案內新增一個類別: SharedFolderHealthCheck 並且實作 IHealthCheck 方法:





此類別在建構時候需要傳入分享資料夾位置;實作方法內我們嘗試寫入一個 test 的文字檔案後刪除,藉此測試分享資料夾是否存在且具有讀寫權限。而後我們透過 try-catch 方式,若有 Exception 發生,則回傳相對應的 HealthCheckResult、Exception 與 Data (相關資料,我們用來儲存分享資料夾路徑,讓使用者知道是哪個路徑錯誤)。


namespace HealthCheckDemo.Services
{
public class SharedFolderHealthCheck : IHealthCheck
{
private string _folderPath;
private Dictionary<string, object> _healthCheckData;
public SharedFolderHealthCheck(string folderPath)
{
_folderPath = folderPath;
_healthCheckData = new Dictionary<string, object>
{
{ "filePath", _folderPath }
};
}
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
try
{
var testFile = $"{_folderPath}\\test.txt";
var fs = File.Create(testFile);
fs.Close();
File.Delete(testFile);
return Task.FromResult(HealthCheckResult.Healthy());
}
catch (Exception e)
{
switch (context.Registration.FailureStatus)
{
case HealthStatus.Degraded:
return Task.FromResult(HealthCheckResult.Degraded($"error when writing to file path", e, _healthCheckData));
case HealthStatus.Healthy:
return Task.FromResult(HealthCheckResult.Healthy($"error when writing to file path", _healthCheckData));
default:
return Task.FromResult(HealthCheckResult.Unhealthy($"error when writing to file path", e, _healthCheckData));
}
}
}
}
}



回到 Startup.cs 檔案中 ConfigureServices 方法,我們加上兩行程式碼,如下圖:


var sharedFolderPath = Configuration["SharedFolderPath"];
services.AddHealthChecks()
.AddSqlServer(connectionString, tags: new[] { "storage" })
.AddRedis(redisString, tags: new[] { "storage" })
.AddUrlGroup(new Uri($"{weatherServiceUri}/weatherforecast"), "Weather API Health Check", HealthStatus.Degraded, timeout: new System.TimeSpan(0, 0, 3), tags: new[] { "service" })
.AddCheck("File Path Health Check", new SharedFolderHealthCheck(sharedFolderPath), HealthStatus.Unhealthy);
view raw HealthCheck.cs hosted with ❤ by GitHub





var sharedFolderPath = Configuration["SharedFolderPath"]; 是從 appsetting.json 中取得路徑,所以我們在 appsetting.json 檔案內需要加上   

"SharedFolderPath": "\\\\DESKTOP-OBC8N7B\\\\SharedFolder"


如下圖所示:




若您有印象,我們在撰寫 SharedFolderHealthCheck  時,將分享資料夾路徑放入 Data 中。我們需要修改一下自訂的 HealthCheckResponse,在回傳內容中增加一個 HealthCheckData 來呈現資料夾路徑。





然後在 Startup.cs 內,先前我們自己寫的 CreateHealthCheckResponse 方法加上

HealthCheckData = string.Join(";", service.Value.Data.Select(x => x.Key + "=" + x.Value).ToArray())





完成後,我們啟動程式:





我們可以嘗試把分享資料夾給關掉,即可看見錯誤訊息發生