blog icon indicating copy to clipboard operation
blog copied to clipboard

Python 使用 logging 模块, 创建 custom handler, 使日志通过 AMQP 发送到 RabbitMQ

Open nkypy opened this issue 8 years ago • 0 comments

创建 handler

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import logging
import pika


class AMQPHandler(logging.Handler):
    def __init__(self, queue_name='cloud.log_record'):
        logging.Handler.__init__(self)
        fmt = '[%(levelname)s]-[%(process)d]-[%(filename)s]-[%(asctime)s]-[%(message)s]'
        formatter = logging.Formatter(fmt)
        self.setFormatter(formatter)
        # 这边rabbitmq链接根据自己设置链接
        connection = pika.BlockingConnection(pika.ConnectionParameters(
            host='localhost'))
        channel = connection.channel()
        self.channel = channel
        self.queue_name = queue_name
        self.channel.queue_declare(queue=queue_name)

    def emit(self, record):
        amqp_data = {
            "device_mac": 'xxxxxx',
            "message": self.format(record)
        }
        self.channel.basic_publish(
            exchange='',
            routing_key=self.queue_name,
            body=json.dumps(amqp_data, ensure_ascii=False))

    def close(self):
        self.channel.close()

上面使用的 self.format(record) 是使用了custom handler 的 formatter, 从而使日志已想要的格式输出, 而使用record.msg则只有内容, 这个地方我踩了无数的坑,现记录下来.

使用方法

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# own logger
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

# adding amqp handler
logger.addHandler(AMQPHandler())
logger.debug('hello')

nkypy avatar Sep 18 '16 08:09 nkypy