> For the complete documentation index, see [llms.txt](https://docs.elven.works/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.elven.works/elven-platform/elven-observability/integracao-e-instrumentacao/nginx/golden-signals-no-nginx.md).

# Golden Signals no NGINX

Este guia mostra como instrumentar qualquer servidor NGINX para expor os 4 Golden Signals — Throughput (taxa), Latência, Erros e Tráfego — utilizando os logs de acesso e um exporter leve baseado em logs.

## Pré-requisitos

* NGINX instalado e configurado.
* Acesso ao arquivo `/var/log/nginx/access.log.`
* Docker ou Docker Compose.
* Prometheus ou OpenTelemetry Collector disponível.
* Grafana para visualização (opcional, mas recomendado).

## Configurar o log do NGINX

### Etapa 1: Atualize o `nginx.conf`

Abra seu `nginx.conf` e adicione o seguinte formato de log:

```
log_format main '$remote_addr - $remote_user [$time_local] '
                '"$request" $status $body_bytes_sent '
                '"$http_referer" "$http_user_agent" "$http_x_forwarded_for" '
                'rt=$request_time '
                'urt=$upstream_response_time '
                'rlen=$request_length '
                'conn=$connection conn_reqs=$connection_requests';

access_log /var/log/nginx/access.log main;
```

**Importante:** Isso adiciona campos essenciais para observabilidade: tempo de requisição, status, método, caminho, tamanho da resposta, entre outros.

### Etapa 2: Reinicie o NGINX

```
sudo nginx -t && nginx -s reload
```

## Subir o Exporter de Logs do NGINX

### Opção A: Docker Compose

```
services:
  nginx_http_metrics:
    image: leonardozwirtes/nginx_http_metrics:latest
    container_name: nginx_http_metrics
    network_mode: host
    ports:
      - "2112:2112"
    environment:
      LOG_PATH: /var/log/nginx/access.log # Ou o caminho correto
    volumes:
      - /var/log/nginx:/var/log/nginx:ro
    restart: unless-stopped
    labels:
      org.label-schema.group: "monitoring"
```

```
docker-compose up -d
```

### Opção B: Docker direto

```
docker run -d \\
  -p 2112:2112 \\
  -v /var/log/nginx:/logs:ro \\
  -e LOG_PATH=/logs/access.log \\
  leonardozwirtes/nginx_http_metrics:latest
```

## Configurar o Prometheus (alternativa)

Adicione ao seu `prometheus.yml:`

```
scrape_configs:
  - job_name: 'nginx_http_metrics'
    static_configs:
      - targets: ['<IP-OU-HOST-DO-EXPORTER>:2112']
```

Exemplo com Docker Compose (caso o Prometheus esteja na mesma rede):

```
scrape_configs:
  - job_name: 'nginx_http_metrics'
    static_configs:
      - targets: ['nginx_http_metrics:2112']
```

**Importante:** Depois reinicie o Prometheus.

## Integrar com o OpenTelemetry Collector **(Melhor)**&#x20;

Se você já usa OpenTelemetry — ou quer uma alternativa mais leve e flexível ao Prometheus — o **Collector é a melhor opção**.

#### Exemplo básico de configuração (`otel-collector-config.yaml`):

```
receivers:
  prometheus:
    config:
      scrape_configs:
        - job_name: 'nginx_http_metrics'
          static_configs:
            - targets: ['nginx_http_metrics:2112']

exporters:
  prometheusremotewrite:
    endpoint: <https://mimir.elvenobservability.com/api/v1/push>

service:
  pipelines:
    metrics:
      receivers: [otlp]
      exporters: [prometheusremotewrite]
```

Para rodar o Collector:

```
otelcol-contrib --config otel-collector-config.yaml
```

**Importante:** Com o Collector, você pode enviar métricas não apenas para o Grafana, Tempo, Loki ou Prometheus — mas também para qualquer backend compatível com OTLP, com total controle de rotas, filtros e transformações.

## Acessar o Endpoint de Métricas

Você pode testar o exporter com:

```
curl <http://localhost:2112/metrics>
```

Ou acessar no navegador:

```
<http://localhost:2112/metrics>
```

Você verá métricas como:

```
http_requests_total
http_duration_seconds_bucket
http_errors_total
http_traffic_bytes_total
```

## Usar o Dashboard Pronto no Grafana

Criamos um dashboard pronto para visualizar todos os Golden Signals do NGINX:

[**Dashboard Grafana: NGINX Golden Signals**](http://elvenobservability.com/)

#### Painéis incluídos:

| Painel                  | Métrica                                                               |
| ----------------------- | --------------------------------------------------------------------- |
| Requisições por segundo | rate(http\_requests\_total\[1m])                                      |
| Taxa de erro (4xx/5xx)  | rate(http\_errors\_total\[1m])                                        |
| Latência P95            | histogram\_quantile(0.95, rate(http\_duration\_seconds\_bucket\[5m])) |
| Tráfego por rota        | rate(http\_traffic\_bytes\_total\[1m])                                |

## Normalização de Paths

Para evitar explosão de cardinalidade nas labels, estas regras são aplicadas:

* `/user/123` → `/user/:id`
* `/api/*` → `/api`
* `.php` → `/:php`
* `.env` → `/:env`
* `/admin/*` → `/admin`
* Qualquer path com mais de 5 barras → `/:complex`

## Resumo

| Etapa                     | Descrição                                    |
| ------------------------- | -------------------------------------------- |
| Configurar o log do NGINX | Adicionar `log_format` ao `nginx.conf`       |
| Subir o exporter          | Via Docker ou Docker Compose                 |
| Coletar as métricas       | Via Prometheus ou Collector                  |
| Acessar métricas          | <http://localhost:2112/metrics>              |
| Visualizar no Grafana     | Usar o Dashboard Golden Signals (link acima) |

## Bônus: Cobertura dos Golden Signals

| Sinal      | Métrica                     |
| ---------- | --------------------------- |
| Throughput | http\_requests\_total       |
| Latência   | http\_duration\_seconds     |
| Erros      | http\_errors\_total         |
| Tráfego    | http\_traffic\_bytes\_total |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.elven.works/elven-platform/elven-observability/integracao-e-instrumentacao/nginx/golden-signals-no-nginx.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
