pattern/observability/logging-sidecar
- Bun
- Elasticsearch
- ElysiaJS
- Fluent Bit
- TypeScript
- Docker
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.
pattern/observability/logging-sidecar
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
Fluxo3 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
API grava JSON no volume compartilhado (src/demo.ts api)
Fluent Bit no mesmo pod (network_mode: service:app) faz tail com offsets no DB
Parser usa o timestamp da linha; modify adiciona pod e namespace
Output es no índice payments-logs; trocar backend = mudar fluent-bit.conf
Trade-offs
O que se ganha, o que se paga
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./
logs/
sidecar/
src/
Executar com Docker
bun install# dependênciasdocker compose up -d --wait# sobe Elasticsearch · Fluent Bitbun run demo# roda o cenáriodocker compose down -vSaí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.
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
Domínio financeiro
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
Parecidos
Por que se relacionam
Seu progresso
0/157 estudados
Fica salvo só neste navegador.