How to write to Kafka from Python logging module?
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
Introduction
If you want Python log records to go directly to Kafka, the standard approach is to write a custom logging.Handler that serializes each log record and hands it to a Kafka producer. The important design choice is not just how to send the message, but how to do it without blocking the application or flushing the producer on every single log call.
Build A Custom Logging Handler
This integrates with Python's logging framework while keeping Kafka concerns inside the handler.
Attach The Handler To A Logger
Now log messages go through the normal logging system and are forwarded to Kafka.
Do Not Flush On Every Emit
A common beginner implementation calls flush() inside emit(). That is simple, but it destroys throughput because every log call waits for producer delivery work.
Bad idea inside emit:
It is usually better to let the Kafka producer batch naturally and flush on shutdown or at controlled checkpoints.
Include Structured Fields
Kafka becomes more useful when logs are structured rather than raw strings.
This makes downstream indexing, filtering, and alerting easier.
Error Handling In A Logging Handler
A logging handler should not crash the whole process if Kafka is temporarily unavailable. Override handleError behavior only when you have a clear policy, and think carefully about whether dropped logs, fallback logging, or retries are appropriate for your application.
Remember that logging infrastructure should usually fail more gracefully than the business path it observes.
Shutdown Cleanly
Because the Kafka producer holds network resources and buffers, close it during application shutdown.
Without an orderly flush and close, buffered log messages may never reach Kafka.
Choice Of Kafka Client
The example above uses kafka-python, which is easy to demonstrate. Some systems prefer confluent-kafka for higher throughput or operational reasons. The logging-handler pattern stays the same even if the producer library changes.
The key abstraction is the logging.Handler, not the exact Kafka client package.
Queue-Based Logging Is Often Better
If Kafka publishing should never slow down the code path producing the log, combine a Kafka handler with QueueHandler and QueueListener so application threads enqueue records and a background thread performs the Kafka I/O. That keeps business logic less exposed to broker latency spikes.
Common Pitfalls
The biggest mistake is flushing on every emit, which turns logging into a latency bottleneck. Another is sending only formatted strings and then regretting the loss of structured fields downstream. Developers also sometimes let Kafka producer exceptions bubble out of emit, which can interfere with normal application execution. Finally, forgetting to close the producer on shutdown can silently drop buffered log records.
Summary
- Send Python logs to Kafka by implementing a custom
logging.Handler. - Serialize log records into structured payloads before sending.
- Avoid flushing on every log event so batching can work.
- Close the producer cleanly to avoid losing buffered messages.
- The handler pattern is the main idea, regardless of which Kafka client library you use.
Related reading
- How ZooKeeper guarantees Single System Image?
- I am trying to run kafka on windoes 10 but erros shows Error Could not find or load main class Files\kafka\libs\activation-1.1.1.jar;C\Program
- I am using Python3 and I want to use RabbitMQ
- I cannot start rabbitmq on my mac
- How to write to TensorBoard in TensorFlow 2
- How to yank to host clipboard from inside a Docker container?
- How to write very long string that conforms with PEP8 and prevent E501
- How vectorizer fit_transform work in sklearn?

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.