> ## Documentation Index
> Fetch the complete documentation index at: https://docs.diyanet.pro/llms.txt
> Use this file to discover all available pages before exploring further.

# Monitoring & Observability

> İki paket — Prometheus HTTP metrikleri ve OpenTelemetry tabanlı tam observability (metrics/tracing + health gauge).

İzleme tarafı iki ayrı pakete bölünür:

* **`BuildingBlocks.Monitoring.Prometheus`** — `prometheus-net` tabanlı, basit HTTP metrik toplama ve `/metrics` endpoint'i.
* **`BuildingBlocks.Observability`** — OpenTelemetry tabanlı tam pipeline: metrics + tracing, instrumentation flag'leri, health-check → Prometheus gauge köprüsü ve master kill-switch.

<Info>
  Prometheus/Grafana/Seq yığınının operasyonel kurulumu için bkz. [Observability](/operations/observability).
</Info>

## BuildingBlocks.Monitoring.Prometheus

`prometheus-net.AspNetCore` üzerine üç extension.

| Metot                       | Tip                     | Etki                                                |
| --------------------------- | ----------------------- | --------------------------------------------------- |
| `AddPrometheusMonitoring()` | `IServiceCollection`    | `UseHttpClientMetrics()` — giden HTTP metrikleri    |
| `UsePrometheusMonitoring()` | `IApplicationBuilder`   | `UseHttpMetrics()` — gelen HTTP metrik middleware'i |
| `MapPrometheusMonitoring()` | `IEndpointRouteBuilder` | `MapMetrics()` — `/metrics` endpoint'i              |

```csharp theme={null}
builder.Services.AddPrometheusMonitoring();

var app = builder.Build();
app.UsePrometheusMonitoring();
app.MapPrometheusMonitoring();   // /metrics
```

## BuildingBlocks.Observability

OTel pipeline'ını tek çağrıyla kurar: `AddDiyanetObservability(configuration)`. `Observability:Enabled = false` ise **hiçbir şey register edilmez** (early-return) — paket "yokmuş gibi" davranır, sıfır maliyet.

| Metot                                    | Tip                     | Etki                                                         |
| ---------------------------------------- | ----------------------- | ------------------------------------------------------------ |
| `AddDiyanetObservability(configuration)` | `IServiceCollection`    | Resource attribute'ları + metrics/tracing + health publisher |
| `MapDiyanetObservabilityEndpoints()`     | `IEndpointRouteBuilder` | `Metrics.Endpoint` (default `/metrics`) Prometheus scrape    |

### `ObservabilityOptions`

`Observability` bölümüne bind edilir. Üç label (`Project`, `Service`, environment) merkezi Grafana'da çoklu projeyi tek template ile yönetmek için kontrattır.

| Üye                     | Varsayılan  | Açıklama                                            |
| ----------------------- | ----------- | --------------------------------------------------- |
| `Enabled`               | `false`     | Master kill-switch. `false` → hiçbir OTel kaydı yok |
| `Project`               | `"unknown"` | Grafana label `project`                             |
| `Service`               | `"api"`     | Grafana label `service`                             |
| `Metrics`               | —           | `MetricsOptions` alt bloğu                          |
| `Tracing`               | —           | `TracingOptions` alt bloğu (default kapalı)         |
| `HealthChecksAsMetrics` | `true`      | `/health/ready` sonuçlarını gauge'a yayınla         |

`MetricsOptions`: `Enabled` (true), `Endpoint` (`/metrics`), `AspNetCore` (true), `HttpClient` (true), `Runtime` (true), `EfCore` (false — cardinality riski), `Redis` (false).

`TracingOptions`: `Enabled` (false), `SampleRatio` (0.1), `OtlpEndpoint` (`http://localhost:4317`).

### Instrumentation flag'leri

`AddDiyanetObservability` her instrumentation'ı yalnızca ilgili flag açıksa ekler:

```csharp theme={null}
otel.WithMetrics(m =>
{
    if (options.Metrics.AspNetCore) m.AddAspNetCoreInstrumentation();
    if (options.Metrics.HttpClient) m.AddHttpClientInstrumentation();
    if (options.Metrics.Runtime)    m.AddRuntimeInstrumentation();
    if (options.Metrics.EfCore)     m.AddMeter("Microsoft.EntityFrameworkCore");
    if (options.Metrics.Redis)      m.AddMeter("OpenTelemetry.Instrumentation.StackExchangeRedis");
    if (options.HealthChecksAsMetrics) m.AddMeter(HealthCheckMetricsPublisher.MeterName);
    m.AddPrometheusExporter();
});

if (options.Tracing.Enabled)
    otel.WithTracing(t =>
    {
        t.SetSampler(new TraceIdRatioBasedSampler(Math.Clamp(options.Tracing.SampleRatio, 0, 1)));
        t.AddAspNetCoreInstrumentation();
        t.AddHttpClientInstrumentation();
        t.AddOtlpExporter(o => o.Endpoint = new Uri(options.Tracing.OtlpEndpoint));
    });
```

### Health-check → gauge köprüsü

`HealthChecksAsMetrics = true` iken `HealthCheckMetricsPublisher` (`IHealthCheckPublisher`) kaydedilir. ASP.NET sağlık altyapısı bunu periyodik tetikler (5 sn delay, 30 sn period); her sonuç bir `ObservableGauge`'a yazılır ve Prometheus scrape ile okunur:

```text theme={null}
diyanet_healthcheck_status{check="postgres", tags="ready,db"} 2
# 2 = Healthy, 1 = Degraded, 0 = Unhealthy
```

Bu, K8s readiness probe için kullanılan `/health/ready` endpoint'inden **bağımsız** çalışır (biri probe, diğeri metrik). Grafana alarm örneği:

```text theme={null}
diyanet_healthcheck_status{check="postgres"} == 0                 # kritik
avg_over_time(diyanet_healthcheck_status[5m]) < 1.5               # flapping
```

### Konfigürasyon

```json theme={null}
{
  "Observability": {
    "Enabled": true,
    "Project": "diyanet",
    "Service": "api",
    "Metrics": { "Enabled": true, "AspNetCore": true, "HttpClient": true, "Runtime": true, "EfCore": false, "Redis": false },
    "Tracing": { "Enabled": false, "SampleRatio": 0.1, "OtlpEndpoint": "http://tempo:4317" },
    "HealthChecksAsMetrics": true
  }
}
```

<Warning>
  `/metrics` dış dünyaya açık **olmamalı** — internal port veya ingress allowlist arkasında olmalı. Public exposure cardinality bombardımanı ve internal endpoint enumeration riski taşır (ör. `location /metrics { allow 10.0.0.0/8; deny all; }`).
</Warning>

<Tip>
  Müşteri matrisi: Prometheus/Grafana yoksa `Enabled=false` (tek satırla komple kapalı, `BuildingBlocks.HealthChecks` yeter). Standart prod: `Enabled=true, Tracing=false`. SRE ekibi: `Tracing=true`.
</Tip>

## İlgili

<CardGroup cols={2}>
  <Card title="Observability" icon="chart-line" href="/operations/observability">
    Prometheus + Grafana + Tempo yığını.
  </Card>

  <Card title="Logging" icon="file-lines" href="/building-blocks/logging">
    Serilog + Seq structured logging.
  </Card>

  <Card title="Operasyon" icon="server" href="/operations/overview">
    Docker ve ortam yönetimi.
  </Card>

  <Card title="Env değişkenleri" icon="sliders" href="/operations/env-variables">
    OBSERVABILITY\_\* ve GRAFANA\_\* anahtarları.
  </Card>
</CardGroup>
