DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Data Engineering
  3. Big Data
  4. Python Custom Logging Handler Example

Python Custom Logging Handler Example

In this post, I am going to write a Python custom logging handler that will send log entries to a Kafka broker where you can aggregate them to a database.

Bill Ward user avatar by
Bill Ward
·
Sep. 01, 18 · Tutorial
Like (1)
Save
Tweet
Share
82.90K Views

Join the DZone community and get the full member experience.

Join For Free

In this post, I am going to write a Python custom logging handler that will send log entries to a Kafka broker where you can aggregate them to a database.

Python's logging module gives you very granular control of how to handle logging from your application. You can log to a file, the console, and more.

It also gives you the ability to write your own logging handlers that let you deal with log entries in any way you want.

This tutorial will cove how to write a Python custom logging handler that will send logs to a Kafka topic.

If you would like to follow along then you must have a Kafka broker configured.

Here are several articles that can help you get one setup:

Ultimate Guide to Installing Kafka Docker on Kubernetes and  Kafka Tutorial for Fast Data Architecture

Or if you like, you can adjust the code to handle the logs as you see fit.

All the code from this tutorial is available on GitHub: https://github.com/admintome/logger2kafka

Creating a Custom Logging Handler Class

To create your custom logging handler class we create a new class that inherits from an existing handler.

For example, in my code I inherited from StreamHandler which sends logs to a stream.

Here is the code for my KafkaHandler class:

from logging import StreamHandler
from mykafka import MyKafka

class KafkaHandler(StreamHandler):

    def __init__(self, broker, topic):
        StreamHandler.__init__(self)
        self.broker = broker
        self.topic = topic

        # Kafka Broker Configuration
        self.kafka_broker = MyKafka(broker)

    def emit(self, record):
        msg = self.format(record)
        self.kafka_broker.send(msg, self.topic)

First we import the handler.

from logging import StreamHandler

Next we declare our class, inheriting from StreamHandler.

class KafkaHandler(StreamHandler):

We define two methods, __init__ and emit.

The __init__ constructor calls the parent's __init__ and sets some class variables.

We also instantiate a  kafka_broker which we will learn about in the next section.

All custom logging handlers need to have an emit() method.

def emit(self, record):
    msg = self.format(record)
    self.kafka_broker.send(msg, self.topic)

The first line formats the message if we have a formatter defined.

The next line sends the formatted message to our Kafka broker topic.

Now lets take a look at our Kafka code.

Python Kafka Producer

The following code defines a Kafka Producer that we use to send messages to a Kafka topic.

from kafka import KafkaProducer
import json


class MyKafka(object):

    def __init__(self, kafka_brokers, json=False):
        self.json = json
        if not json:
            self.producer = KafkaProducer(
                bootstrap_servers=kafka_brokers
            )
        else:
            self.producer = KafkaProducer(
                value_serializer=lambda v: json.dumps(v).encode('utf-8'),
                bootstrap_servers=kafka_brokers
            )

    def send(self, data, topic):
        if self.json:
            result = self.producer.send(topic, key=b'log', value=data)
        else:
            result = self.producer.send(topic, bytes(data, 'utf-8'))
        print("kafka send result: {}".format(result.get()))

This class makes use of the KafkaProducer class from the Kafka Python Module.

Our class is actually an expanded version from earlier articles. This version lets you send JSON data in addition to string data.

In the __init__ constructor we set json to False (default) if we want to send string data.

Conversely, if we want to send JSON data then we set the json parameter to True.

The constructor configures a producer object that handles Kafka Producer requests.

We also define a send method that we will use to send data to a Kafka topic.

We are now ready to tie it all together with a sample application.

Python Custom Logging Handler

Our sample application will be a simple for loop that will accept input and push the text to our logging.

Logging will be configured to send to three different places: the console, a file, and Kafka.

Here is our sample application.

import logging
from kafkahandler import KafkaHandler


class Main:

    def __init__(self):
        logging.basicConfig(
            format='%(asctime)s %(levelname)s %(message)s', 
            level=logging.INFO, 
            datefmt='%m/%d/%Y %I:%M:%S %p'
            )
        self.logger = logging.getLogger('simple_example')
        ch = logging.StreamHandler()
        ch.setLevel(logging.INFO)
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        ch.setFormatter(formatter)
        self.logger.addHandler(ch)
        fl = logging.FileHandler("myapp.log")
        self.logger.addHandler(fl)
        kh = KafkaHandler("192.168.1.240:9092", "pylog")
        kh.setLevel(logging.INFO)
        self.logger.addHandler(kh)



    def run(self):
        while True:
            log = input("> ")
            self.logger.info(log)

if __name__ == "__main__":
    main = Main()
    main.run()

First we configure Python logging with basicConfig.

logging.basicConfig(
            format='%(asctime)s %(levelname)s %(message)s', 
            level=logging.INFO, 
            datefmt='%m/%d/%Y %I:%M:%S %p'
            )

Here we set the logging options like what the format, logging level, and date format for console logging.

Next we configure our StreamHandler.

        self.logger = logging.getLogger('simple_example')
        ch = logging.StreamHandler()
        ch.setLevel(logging.INFO)
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        ch.setFormatter(formatter)
        self.logger.addHandler(ch)

We log to the file with a couple of lines:

       fl = logging.FileHandler("myapp.log")
       self.logger.addHandler(fl)

The next several lines create our custom KafkaHandler:

kh = KafkaHandler("192.168.1.240:9092", "pylog")
kh.setLevel(logging.INFO)
self.logger.addHandler(kh)

Running the program we enter in some text and hit enter.

> this is an awsome log
2018-08-29 14:24:52,425 - simple_example - INFO - this is an awsome log
kafka send result: RecordMetadata(topic='pylog', partition=0, topic_partition=TopicPartition(topic='pylog', partition=0), offset=2, timestamp=1535570692427, checksum=None, serialized_key_size=-1, serialized_value_size=21)
08/29/2018 02:24:52 PM INFO this is an awsome log
>

We can see that it send the log to the console and our Kafka Broker.

I setup a Kafka Consumer using the kafka-console-consumer script that comes with Kafka.

$ bin/kafka-console-consumer.sh --bootstrap-server 192.168.1.240:9092 --topic pylog --from-beginning
this is an awsome log

We can see that my consumer received the log message.

Conclusion

I hope that you have enjoyed this post.

If you did then please share it and comment below.

kafka Python (language)

Published at DZone with permission of Bill Ward, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • A Beginner's Guide to Infrastructure as Code
  • Keep Your Application Secrets Secret
  • Best Navicat Alternative for Windows
  • 5 Best Python Testing Frameworks

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: