Pular para o conteúdo

Sidecar de Logs

Um container auxiliar no mesmo pod (volume, rede, ciclo de vida) assume o envio de logs: a API escreve JSON em arquivo e o Fluent Bit enriquece e envia ao Elasticsearch.

passos
4
arquivos
9
testes
0
tecnologias
6

Cenário

PIX com timeout no BACEN: a API só grava no arquivo; no Elasticsearch as linhas chegam com o horário da aplicação, pod e namespace.

Planta

Fluxo
3/3
pod payments-api-7f9c4API de pagamentos- JSON em arquivovolume compartilhadoFluent Bit - tail,parser, modifyElasticsearch -payments-logsappendtail com offsetspod e namespaceadicionados
3

3 passos — reproduza para seguir o fluxo

Como funciona

4passos

Container auxiliar no mesmo pod (volume, rede, ciclo de vida) assume o envio de logs

Esconde cada passo: lembre antes de tocar para revelar.

Vocabulário compartilhado

timestamp+1
  1. 1

    API grava JSON no volume compartilhado (src/demo.ts api)

  2. 2

    Fluent Bit no mesmo pod (network_mode: service:app) faz tail com offsets no DB

  3. 3

    Parser usa o timestamp da linha; modify adiciona pod e namespace

  4. 4

    Output es no índice payments-logs; trocar backend = mudar fluent-bit.conf

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Aplicação sem backend nem retry de log

  • Metadados fora do código

Custos

  • Container a mais por pod

  • Formato da linha é contrato

Código

pattern/observability/logging-sidecar

9 arquivos

./

  • .env.exampleinfra
  • docker-compose.ymlinfra
  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

logs/

  • .gitignore

sidecar/

  • fluent-bit.conf
  • parsers.conf

src/

  • demo.tsdemo

Executar com Docker

  1. bun install# dependências
  2. docker compose up -d --wait# sobe Elasticsearch · Fluent Bit
  3. bun run demo# roda o cenário
  4. docker compose down -v

Saída: a API responde outcome: reverted; no Elasticsearch, pix settlement started (info) e pix settlement failed (error), ambas com pod=payments-api-7f9c4 e namespace=payments.

Requisitos
BunDocker
Sobe junto
ElasticsearchFluent Bit

Código

src/demo.ts

// Demo: the payments API only appends JSON lines to a file; the Fluent Bit sidecar in the same pod ships them to Elasticsearch with the pod's metadata.
import { appendFileSync } from "node:fs";
import { Elysia, t } from "elysia";

const ELASTICSEARCH_URL = Bun.env.LOGGING_SIDECAR_ELASTICSEARCH_URL ?? "http://localhost:9200";
const PAYMENTS_URL = Bun.env.LOGGING_SIDECAR_PAYMENTS_URL ?? "http://localhost:3000";
const PAYMENTS_PORT = 3000;

// With argument "api" this file is the pod's main container (see docker-compose.yml): no log shipper, backend address or retry in it.
if (Bun.argv[2] === "api") {
  const logFile = Bun.env.LOGGING_SIDECAR_LOG_FILE ?? "logs/payments.log";
  // One append per line keeps whole lines, so the sidecar's tail never reads half an event.
  const log = (level: string, correlationId: string, message: string, fields: Record<string, unknown> = {}) =>
    appendFileSync(logFile, `${JSON.stringify({ ...fields, timestamp: new Date().toISOString(), level, service: "svc-payments", correlationId, message })}\n`);
  new Elysia()
    .get("/health", () => "ok")
    .post("/pix", ({ body }) => {
      log("info", body.pixId, "pix settlement started", { amountCents: body.amountCents });
      log("error", body.pixId, "pix settlement failed", { errorCode: "BACEN_TIMEOUT", attemptNumber: 3 });
      return { pixId: body.pixId, outcome: "reverted" };
    }, { body: t.Object({ pixId: t.String(), amountCents: t.Integer({ minimum: 1 }) }) })
    .listen(PAYMENTS_PORT);
} else {
  const pixId = `PIX-${Date.now()}`;
  const response = await fetch(`${PAYMENTS_URL}/pix`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ pixId, amountCents: 12_500 }) });
  console.log(`  [PAYMENTS] ${JSON.stringify(await response.json())}`);
  // The sidecar ships asynchronously: wait until both lines of this PIX are searchable.
  let hits: Record<string, unknown>[] = [];
  while (hits.length < 2) {
    await Bun.sleep(500);
    const search = await fetch(`${ELASTICSEARCH_URL}/payments-logs/_search`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ query: { term: { "correlationId.keyword": pixId } }, sort: [{ "@timestamp": "asc" }] }) });
    hits = search.ok ? ((await search.json()) as { hits: { hits: { _source: Record<string, unknown> }[] } }).hits.hits.map((hit) => hit._source) : [];
  }
  for (const line of hits) console.log(`  [ELASTICSEARCH] ${line["@timestamp"]} ${line.level} ${line.message} pod=${line.pod} namespace=${line.namespace}`);
}

Nível

intermediário

6/13

Linhas de TypeScript
33
Tipo
B — dois ou mais serviços (docker compose)

Domínio financeiro

  • PIX
  • Conta corrente
  • BACEN/SPI

Padrões do catálogo que implementa

Infraestrutura

  • Elasticsearchmotor de busca

    elasticsearch:8.15.0:9200

  • Bun (container)runtime

    oven/bun:1.3-alpine:3000

  • Fluent Bitcoletor de logs

    fluent/fluent-bit:3.2

Variáveis de ambiente

LOGGING_SIDECAR_PAYMENTS_URL
http://localhost:3000
Payments API (the pod's main container) and Elasticsearch, as seen by the demo.
LOGGING_SIDECAR_ELASTICSEARCH_URL
http://localhost:9200
LOGGING_SIDECAR_LOG_FILE
logs/payments.log
File the API appends to; docker-compose.yml points it at the shared volume.

Parecidos

Esc

↑ ↓ navegarEnter abrir239 resultados