Inside a logging service
medium 30 minA logging service carries the log lines of all programs to one place where people can search them.
A tiny logging pipeline
Read it, run it, change a line and run it again.
Loading editor…
Plain Python: structured lines, masking, a bounded buffer, an inverted index and a search. The variants show a Kafka logger.
The same in TypeScript
import { Kafka } from "kafkajs";import { randomUUID } from "node:crypto";type Level = "DEBUG" | "INFO" | "WARN" | "ERROR" | "FATAL";interface Entry { id: string; timestamp: string; level: Level; service: string; traceId?: string; spanId?: string; message: string; context: Record<string, unknown>; metadata: { host: string; environment: string; version: string };}export class DistributedLogger { private producer; private buffer: Entry[] = []; private timer?: NodeJS.Timeout; private flushing = false; dropped = 0; constructor(private service: string, brokers: string[], private max = 10_000) { this.producer = new Kafka({ clientId: service, brokers }).producer(); } async connect() { await this.producer.connect(); this.timer = setInterval(() => void this.flush(), 1000); } // Returns at once. Nothing here waits for the network. log(level: Level, message: string, context: Record<string, unknown> = {}, trace?: { traceId: string; spanId: string }) { if (this.buffer.length >= this.max) { this.dropped++; return; } this.buffer.push({ id: randomUUID(), timestamp: new Date().toISOString(), level, service: this.service, ...trace, message, context, metadata: { host: process.env.HOSTNAME ?? "unknown", environment: process.env.NODE_ENV ?? "development", version: process.env.APP_VERSION ?? "0.0.0", }, }); if (this.buffer.length >= 100) void this.flush(); } async flush() { if (this.flushing || this.buffer.length === 0) return; this.flushing = true; const batch = this.buffer.splice(0, 100); try { await this.producer.send({ topic: "application-logs", messages: batch.map((e) => ({ key: e.traceId ?? null, value: JSON.stringify(e) })), }); } catch { this.buffer.unshift(...batch); // the ids make a second copy harmless } finally { this.flushing = false; } } async disconnect() { clearInterval(this.timer); let before = -1; while (this.buffer.length && this.buffer.length !== before) { before = this.buffer.length; await this.flush(); } await this.producer.disconnect(); }}const logger = new DistributedLogger("order-service", ["kafka:9092"]);await logger.connect();logger.log("INFO", "order created", { orderId: "12345" });logger.log("ERROR", "payment failed", { orderId: "12345", errorName: "Timeout" });The same in Java
public final class DistributedLogger implements AutoCloseable { public enum Level { DEBUG, INFO, WARN, ERROR, FATAL } public record Entry(String id, String timestamp, String level, String service, String traceId, String spanId, String message, Map<String, Object> context, Map<String, String> metadata) {} private final BlockingQueue<Entry> buffer = new ArrayBlockingQueue<>(10_000); private final AtomicLong dropped = new AtomicLong(); private final KafkaProducer<String, String> producer; private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); private final ObjectMapper json = new ObjectMapper(); private final String service; private final Map<String, String> metadata = Map.of( "host", System.getenv().getOrDefault("HOSTNAME", "unknown"), "environment", System.getenv().getOrDefault("ENV", "development"), "version", System.getenv().getOrDefault("APP_VERSION", "0.0.0")); public DistributedLogger(String service, Properties kafka) { this.service = service; this.producer = new KafkaProducer<>(kafka, new StringSerializer(), new StringSerializer()); scheduler.scheduleWithFixedDelay(this::flush, 1, 1, TimeUnit.SECONDS); } /** offer() never waits: a full buffer drops the line and counts it. */ public void log(Level level, String message, String traceId, String spanId, Map<String, Object> context) { Entry e = new Entry(UUID.randomUUID().toString(), Instant.now().toString(), level.name(), service, traceId, spanId, message, context, metadata); if (!buffer.offer(e)) dropped.incrementAndGet(); } private void flush() { List<Entry> batch = new ArrayList<>(); buffer.drainTo(batch); for (Entry e : batch) { try { producer.send(new ProducerRecord<>("application-logs", e.traceId(), json.writeValueAsString(e)), (meta, error) -> { if (error != null) dropped.incrementAndGet(); }); } catch (Exception ex) { dropped.incrementAndGet(); } } } @Override public void close() { scheduler.shutdown(); flush(); producer.close(); // waits for what was sent }}