Python Script to Send Log Messages to Kafka
This Python script demonstrates how to send log messages to a Kafka topic using thekafka-python library. The script initializes a Kafka producer, serializes log messages to JSON, and sends them to a specified Kafka topic.
Python Script
Configuration Details
Kafka Configuration
-
KAFKA_BROKER:- The address of the Kafka broker. Change this to the appropriate address of your Kafka instance.
- Example:
kafka.example.in:9092
-
KAFKA_TOPIC:- The Kafka topic to which the log message will be sent. Modify this based on your use case.
- Example:
'project1logs'
Producer Initialization
KafkaProducer:bootstrap_servers: Address of the Kafka broker(s).value_serializer: Function to serialize the log message into JSON format. Thelambda v: json.dumps(v).encode('utf-8')converts the log message into a JSON string and encodes it to UTF-8.
Log Message
log_message:- A sample log message with fields such as
level,message, andtimestamp. Adjust this message based on your logging needs.
- A sample log message with fields such as
Sending the Message
producer.send:- Sends the log message to the specified Kafka topic.
producer.flush:- Ensures all messages are sent before closing the producer.
producer.close:- Closes the producer connection.
Usage
-
Install Dependencies:
Make sure you have the
kafka-pythonlibrary installed. You can install it using pip: -
Run the Script:
Execute the Python script to send a log message to Kafka:
- Verify: Check your Kafka topic to ensure that the log message has been sent and is available.
Notes
- Error Handling: For a production script, consider adding error handling and logging to manage any issues with connecting to Kafka or sending messages.
- Security: If your Kafka broker requires authentication or uses SSL, you’ll need to add additional configuration to the
KafkaProducer.
This script provides a basic example of sending log messages to Kafka. Adjust the configuration and message format as needed for your specific use case.
Setup Venv :
The error you’re encountering is due to PEP 668, which prevents pip from modifying system-managed Python environments (like the one installed viaapt). This is a safety feature in newer Debian/Ubuntu systems.
To resolve this cleanly and safely, create and use a virtual environment.
