umbraco-health-check

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Umbraco Health Check

Umbraco健康检查

What is it?

什么是健康检查?

Health Checks in Umbraco allow you to create custom system diagnostics that appear in the Health Check dashboard. They verify that your Umbraco installation and related services are functioning correctly. Health checks can report status, display warnings, and provide actionable recommendations for resolving issues.
Umbraco中的健康检查功能允许你创建自定义系统诊断,这些诊断会显示在健康检查仪表盘中。它们可验证你的Umbraco安装及相关服务是否正常运行。健康检查可以报告状态、显示警告,并提供解决问题的可行建议。

Documentation

相关文档

Related Foundation Skills

相关基础技能

  • Context API: When accessing application state
    • Reference skill:
      umbraco-context-api
  • Controllers: When creating API endpoints for checks
    • Reference skill:
      umbraco-controllers
  • Context API:访问应用程序状态时使用
    • 参考技能:
      umbraco-context-api
  • Controllers:为检查创建API端点时使用
    • 参考技能:
      umbraco-controllers

Workflow

实现流程

  1. Fetch docs - Use WebFetch on the URLs above
  2. Ask questions - What should be checked? What actions to provide?
  3. Generate files - Create manifest + context based on latest docs
  4. Explain - Show what was created and how to test
  1. 获取文档 - 使用WebFetch获取上述URL中的文档
  2. 梳理需求 - 确定需要检查哪些内容?提供哪些操作?
  3. 生成文件 - 根据最新文档创建清单(manifest)和上下文(context)文件
  4. 说明解释 - 展示创建的内容以及测试方法

Minimal Examples

最简示例

Manifest (manifests.ts)

清单文件(manifests.ts)

typescript
import type { ManifestHealthCheck } from '@umbraco-cms/backoffice/health-check';

export const manifests: Array<ManifestHealthCheck> = [
  {
    type: 'healthCheck',
    alias: 'My.HealthCheck.Custom',
    name: 'Custom Health Check',
    api: () => import('./my-health-check.context.js'),
    meta: {
      label: 'Custom Check',
    },
  },
];
typescript
import type { ManifestHealthCheck } from '@umbraco-cms/backoffice/health-check';

export const manifests: Array<ManifestHealthCheck> = [
  {
    type: 'healthCheck',
    alias: 'My.HealthCheck.Custom',
    name: 'Custom Health Check',
    api: () => import('./my-health-check.context.js'),
    meta: {
      label: 'Custom Check',
    },
  },
];

Context Implementation (my-health-check.context.ts)

上下文实现(my-health-check.context.ts)

typescript
import { UmbHealthCheckContext } from '@umbraco-cms/backoffice/health-check';
import type { UmbControllerHost } from '@umbraco-cms/backoffice/controller-api';
import type { HealthCheckResultResponseModel } from '@umbraco-cms/backoffice/external/backend-api';

export class MyHealthCheckContext extends UmbHealthCheckContext {
  constructor(host: UmbControllerHost) {
    super(host);
  }

  override async check(): Promise<HealthCheckResultResponseModel> {
    // Perform your health check logic
    const isHealthy = await this.#performCheck();

    return {
      message: isHealthy ? 'All systems operational' : 'Issue detected',
      resultType: isHealthy ? 'Success' : 'Warning',
      actions: isHealthy ? [] : [
        {
          alias: 'fix-issue',
          name: 'Fix Issue',
          description: 'Attempt to automatically fix this issue',
        },
      ],
    };
  }

  async #performCheck(): Promise<boolean> {
    // Your custom check logic here
    return true;
  }

  override async executeAction(actionAlias: string): Promise<HealthCheckResultResponseModel> {
    if (actionAlias === 'fix-issue') {
      // Execute the fix action
      return {
        message: 'Issue has been resolved',
        resultType: 'Success',
        actions: [],
      };
    }

    return {
      message: 'Unknown action',
      resultType: 'Error',
      actions: [],
    };
  }
}

export { MyHealthCheckContext as api };
typescript
import { UmbHealthCheckContext } from '@umbraco-cms/backoffice/health-check';
import type { UmbControllerHost } from '@umbraco-cms/backoffice/controller-api';
import type { HealthCheckResultResponseModel } from '@umbraco-cms/backoffice/external/backend-api';

export class MyHealthCheckContext extends UmbHealthCheckContext {
  constructor(host: UmbControllerHost) {
    super(host);
  }

  override async check(): Promise<HealthCheckResultResponseModel> {
    // Perform your health check logic
    const isHealthy = await this.#performCheck();

    return {
      message: isHealthy ? 'All systems operational' : 'Issue detected',
      resultType: isHealthy ? 'Success' : 'Warning',
      actions: isHealthy ? [] : [
        {
          alias: 'fix-issue',
          name: 'Fix Issue',
          description: 'Attempt to automatically fix this issue',
        },
      ],
    };
  }

  async #performCheck(): Promise<boolean> {
    // Your custom check logic here
    return true;
  }

  override async executeAction(actionAlias: string): Promise<HealthCheckResultResponseModel> {
    if (actionAlias === 'fix-issue') {
      // Execute the fix action
      return {
        message: 'Issue has been resolved',
        resultType: 'Success',
        actions: [],
      };
    }

    return {
      message: 'Unknown action',
      resultType: 'Error',
      actions: [],
    };
  }
}

export { MyHealthCheckContext as api };

Interface Reference

接口参考

typescript
interface ManifestHealthCheck extends ManifestBase {
  type: 'healthCheck';
  api: ApiLoaderProperty; // Should implement UmbHealthCheckContext
  meta: MetaHealthCheck;
}

interface MetaHealthCheck {
  label: string;
}

// Result types: 'Success' | 'Warning' | 'Error' | 'Info'
interface HealthCheckResultResponseModel {
  message: string;
  resultType: string;
  actions?: Array<{
    alias: string;
    name: string;
    description?: string;
  }>;
}
typescript
interface ManifestHealthCheck extends ManifestBase {
  type: 'healthCheck';
  api: ApiLoaderProperty; // Should implement UmbHealthCheckContext
  meta: MetaHealthCheck;
}

interface MetaHealthCheck {
  label: string;
}

// Result types: 'Success' | 'Warning' | 'Error' | 'Info'
interface HealthCheckResultResponseModel {
  message: string;
  resultType: string;
  actions?: Array<{
    alias: string;
    name: string;
    description?: string;
  }>;
}

Backend C# Health Check

后端C#健康检查

Health checks can also be implemented as C# classes that are auto-discovered by Umbraco.
csharp
using Umbraco.Cms.Core.HealthChecks;

namespace MyPackage.HealthChecks;

[HealthCheck(
    "12345678-1234-1234-1234-123456789012",
    "My Custom Check",
    Description = "Verifies custom services are running",
    Group = "Custom")]
public class MyHealthCheck : HealthCheck
{
    public MyHealthCheck(HealthCheckContext context) : base(context) { }

    public override Task<IEnumerable<HealthCheckStatus>> GetStatus()
    {
        var isHealthy = CheckMyService();
        var status = new HealthCheckStatus(isHealthy ? "Service running" : "Service down")
        {
            ResultType = isHealthy ? StatusResultType.Success : StatusResultType.Error,
            Actions = isHealthy ? null : new List<HealthCheckAction>
            {
                new("restart", Id) { Name = "Restart Service" }
            }
        };
        return Task.FromResult<IEnumerable<HealthCheckStatus>>(new[] { status });
    }

    public override HealthCheckStatus ExecuteAction(HealthCheckAction action)
    {
        if (action.Alias == "restart")
        {
            RestartMyService();
            return new HealthCheckStatus("Restarted") { ResultType = StatusResultType.Success };
        }
        throw new InvalidOperationException("Unknown action");
    }

    private bool CheckMyService() => true;
    private void RestartMyService() { }
}
健康检查也可以实现为C#类,Umbraco会自动发现这些类。
csharp
using Umbraco.Cms.Core.HealthChecks;

namespace MyPackage.HealthChecks;

[HealthCheck(
    "12345678-1234-1234-1234-123456789012",
    "My Custom Check",
    Description = "Verifies custom services are running",
    Group = "Custom")]
public class MyHealthCheck : HealthCheck
{
    public MyHealthCheck(HealthCheckContext context) : base(context) { }

    public override Task<IEnumerable<HealthCheckStatus>> GetStatus()
    {
        var isHealthy = CheckMyService();
        var status = new HealthCheckStatus(isHealthy ? "Service running" : "Service down")
        {
            ResultType = isHealthy ? StatusResultType.Success : StatusResultType.Error,
            Actions = isHealthy ? null : new List<HealthCheckAction>
            {
                new("restart", Id) { Name = "Restart Service" }
            }
        };
        return Task.FromResult<IEnumerable<HealthCheckStatus>>(new[] { status });
    }

    public override HealthCheckStatus ExecuteAction(HealthCheckAction action)
    {
        if (action.Alias == "restart")
        {
            RestartMyService();
            return new HealthCheckStatus("Restarted") { ResultType = StatusResultType.Success };
        }
        throw new InvalidOperationException("Unknown action");
    }

    private bool CheckMyService() => true;
    private void RestartMyService() { }
}

Best Practices

最佳实践

  • Return clear, actionable messages
  • Provide fix actions when possible
  • Use appropriate result types (Success, Warning, Error, Info)
  • Consider performance - health checks run periodically
That's it! Always fetch fresh docs, keep examples minimal, generate complete working code.
  • 返回清晰、可执行的提示信息
  • 尽可能提供修复操作
  • 使用合适的结果类型(Success、Warning、Error、Info)
  • 考虑性能因素——健康检查会定期运行
以上就是全部内容!请务必获取最新文档,保持示例简洁,生成可直接运行的完整代码。