Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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.

Pythons 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

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.

Also be sure to subscribe to the AdminTome Blog Newsletter

The post Python Custom Logging Handler Example appeared first on AdminTome Blog.



This post first appeared on AdminTome, please read the originial post: here

Share the post

Python Custom Logging Handler Example

×

Subscribe to Admintome

Get updates delivered right to your inbox!

Thank you for your subscription

×